Skip to content

Automate browser based workflows with AI

SKY-10944: Add PDF Fill workflow block (local AcroForm + flat-PDF OCR fill) (#6622)

Suchintanedd80635d27c
diff --git a/skyvern-frontend/src/routes/workflows/editor/collapse/collapsibleBlockTypes.ts b/skyvern-frontend/src/routes/workflows/editor/collapse/collapsibleBlockTypes.ts
index 4aa83adbe..703434990 100644
--- a/skyvern-frontend/src/routes/workflows/editor/collapse/collapsibleBlockTypes.ts
+++ b/skyvern-frontend/src/routes/workflows/editor/collapse/collapsibleBlockTypes.ts
@@ -29,6 +29,7 @@ const COLLAPSIBLE_NODE_TYPE_TO_BLOCK_TYPE: Record<string, WorkflowBlockType> = {
workflowTrigger: "workflow_trigger",
googleSheetsRead: "google_sheets_read",
googleSheetsWrite: "google_sheets_write",
+ pdfFill: "pdf_fill",
loop: "for_loop",
conditional: "conditional",
};
diff --git a/skyvern-frontend/src/routes/workflows/editor/helpContent.ts b/skyvern-frontend/src/routes/workflows/editor/helpContent.ts
index 6e40bf645..3e4450c71 100644
--- a/skyvern-frontend/src/routes/workflows/editor/helpContent.ts
+++ b/skyvern-frontend/src/routes/workflows/editor/helpContent.ts
@@ -73,6 +73,16 @@ export const helpTooltips = {
prompt:
"Write a prompt you would like passed into the LLM and specify the output format, if applicable.",
},
+ pdf_fill: {
+ ...baseHelpTooltipContent,
+ fileUrl:
+ "The source PDF URL, S3 URI, or file path from an earlier block output.",
+ prompt:
+ "Describe how to fill the PDF fields. Use {{ parameter_name }} references when needed.",
+ payload:
+ "Structured JSON data sent to the field-mapping model. Supports the {{ parameter | json }} filter.",
+ llmKey: "Optional LLM key override for the field-mapping step.",
+ },
google_sheets_read: {
...baseHelpTooltipContent,
spreadsheetUrl:
diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/PdfFillNode/PdfFillEditor.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/PdfFillNode/PdfFillEditor.tsx
new file mode 100644
index 000000000..1cc071b35
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/PdfFillNode/PdfFillEditor.tsx
@@ -0,0 +1,197 @@
+import { PlusIcon } from "@radix-ui/react-icons";
+import { useEdges, useNodes, useNodesData } from "@xyflow/react";
+import { useCallback } from "react";
+
+import { HelpTooltip } from "@/components/HelpTooltip";
+import { ModelSelector } from "@/components/ModelSelector";
+import { WorkflowBlockInput } from "@/components/WorkflowBlockInput";
+import { WorkflowBlockInputTextarea } from "@/components/WorkflowBlockInputTextarea";
+import {
+ Accordion,
+ AccordionContent,
+ AccordionItem,
+ AccordionTrigger,
+} from "@/components/ui/accordion";
+import { Button } from "@/components/ui/button";
+import { Label } from "@/components/ui/label";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import { CodeEditor } from "@/routes/workflows/components/CodeEditor";
+
+import { helpTooltips } from "../../helpContent";
+import { getAvailableOutputParameterKeys } from "../../workflowEditorUtils";
+import { IgnoreWorkflowSystemPrompt } from "../IgnoreWorkflowSystemPrompt";
+import { type AppNode } from "..";
+import { JsonValidator } from "../HttpRequestNode/HttpUtils";
+import { ParametersMultiSelect } from "../TaskNode/ParametersMultiSelect";
+import { WorkflowBlockParameterSelect } from "../WorkflowBlockParameterSelect";
+import { useUpdate } from "../../useUpdate";
+import { type PdfFillNode, type PdfFillNodeData } from "./types";
+
+function PdfFillEditor({ blockId }: { blockId: string }) {
+ const nodeSlice = useNodesData<PdfFillNode>(blockId);
+ if (!nodeSlice || nodeSlice.type !== "pdfFill") {
+ return null;
+ }
+ return <PdfFillEditorBody blockId={blockId} data={nodeSlice.data} />;
+}
+
+function PdfFillEditorBody({
+ blockId,
+ data,
+}: {
+ blockId: string;
+ data: PdfFillNodeData;
+}) {
+ const { editable } = data;
+ const nodes = useNodes<AppNode>();
+ const edges = useEdges();
+ const availableOutputParameterKeys = getAvailableOutputParameterKeys(
+ nodes,
+ edges,
+ blockId,
+ );
+ const update = useUpdate<PdfFillNodeData>({ id: blockId, editable });
+
+ const handleAddParameterToPayload = useCallback(
+ (parameterKey: string) => {
+ const parameterSyntax = `{{ ${parameterKey} | json }}`;
+ const currentPayload = data.payload || "{}";
+ try {
+ const parsed = JSON.parse(currentPayload);
+ const existingKeys = Object.keys(parsed);
+ let keyIndex = existingKeys.length + 1;
+ let newKey = `param_${keyIndex}`;
+ while (existingKeys.includes(newKey)) {
+ keyIndex++;
+ newKey = `param_${keyIndex}`;
+ }
+ parsed[newKey] = parameterSyntax;
+ update({ payload: JSON.stringify(parsed, null, 2) });
+ } catch {
+ update({
+ payload: JSON.stringify({ param_1: parameterSyntax }, null, 2),
+ });
+ }
+ },
+ [data.payload, update],
+ );
+
+ return (
+ <div data-testid="pdf-fill-block-form" className="space-y-4">
+ <div className="space-y-2">
+ <div className="flex gap-2">
+ <Label className="text-xs text-slate-300">File URL</Label>
+ <HelpTooltip content={helpTooltips["pdf_fill"]["fileUrl"]} />
+ </div>
+ <WorkflowBlockInput
+ nodeId={blockId}
+ value={data.fileUrl}
+ onChange={(next) => update({ fileUrl: next })}
+ className="nopan text-xs"
+ />
+ </div>
+
+ <div className="space-y-2">
+ <div className="flex gap-2">
+ <Label className="text-xs text-slate-300">Prompt</Label>
+ <HelpTooltip content={helpTooltips["pdf_fill"]["prompt"]} />
+ </div>
+ <WorkflowBlockInputTextarea
+ nodeId={blockId}
+ value={data.prompt}
+ onChange={(next) => update({ prompt: next })}
+ className="nopan text-xs"
+ placeholder="Fill the form using the payload."
+ />
+ </div>
+
+ <div className="space-y-2">
+ <div className="flex items-center justify-between">
+ <div className="flex gap-2">
+ <Label className="text-xs text-slate-300">Payload</Label>
+ <HelpTooltip content={helpTooltips["pdf_fill"]["payload"]} />
+ </div>
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-7 px-2 text-xs"
+ disabled={!editable}
+ >
+ <PlusIcon className="mr-1 h-3 w-3" />
+ Add Input
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent className="w-[22rem]">
+ <WorkflowBlockParameterSelect
+ nodeId={blockId}
+ onAdd={handleAddParameterToPayload}
+ />
+ </PopoverContent>
+ </Popover>
+ </div>
+ <CodeEditor
+ className="w-full"
+ language="json"
+ value={data.payload}
+ onChange={(next) => update({ payload: next || "{}" })}
+ readOnly={!editable}
+ minHeight="120px"
+ maxHeight="220px"
+ />
+ <JsonValidator value={data.payload} />
+ </div>
+
+ <ModelSelector
+ className="nopan w-52 text-xs"
+ value={data.model}
+ onChange={(value) => update({ model: value })}
+ />
+ <IgnoreWorkflowSystemPrompt
+ ignoreWorkflowSystemPrompt={data.ignoreWorkflowSystemPrompt ?? false}
+ editable={editable}
+ onIgnoreWorkflowSystemPromptChange={(ignoreWorkflowSystemPrompt) => {
+ update({ ignoreWorkflowSystemPrompt });
+ }}
+ />
+
+ <Accordion type="single" collapsible>
+ <AccordionItem value="advanced" className="border-b-0">
+ <AccordionTrigger className="py-0">
+ Advanced Settings
+ </AccordionTrigger>
+ <AccordionContent className="pl-6 pr-1 pt-1">
+ <div className="space-y-4">
+ <ParametersMultiSelect
+ availableOutputParameters={availableOutputParameterKeys}
+ parameters={data.parameterKeys}
+ onParametersChange={(parameterKeys) => {
+ update({ parameterKeys });
+ }}
+ />
+ <div className="space-y-2">
+ <div className="flex gap-2">
+ <Label className="text-xs text-slate-300">LLM Key</Label>
+ <HelpTooltip content={helpTooltips["pdf_fill"]["llmKey"]} />
+ </div>
+ <WorkflowBlockInput
+ nodeId={blockId}
+ value={data.llmKey}
+ onChange={(next) => update({ llmKey: next })}
+ className="nopan text-xs"
+ />
+ </div>
+ </div>
+ </AccordionContent>
+ </AccordionItem>
+ </Accordion>
+ </div>
+ );
+}
+
+export { PdfFillEditor };
diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/PdfFillNode/PdfFillNode.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/PdfFillNode/PdfFillNode.tsx
new file mode 100644
index 000000000..45952d5ef
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/PdfFillNode/PdfFillNode.tsx
@@ -0,0 +1,76 @@
+import { Handle, NodeProps, Position } from "@xyflow/react";
+import { useParams } from "react-router-dom";
+
+import { statusIsRunningOrQueued } from "@/routes/tasks/types";
+import { useWorkflowRunQuery } from "@/routes/workflows/hooks/useWorkflowRunQuery";
+import { useRecordingStore } from "@/store/useRecordingStore";
+import { cn } from "@/util/utils";
+
+import { useCollapseContext } from "../../collapse/CollapseContext";
+import { NodeBody } from "../../collapse/NodeBody";
+import { BuildModeOnly } from "../BuildModeOnly";
+import { NodeHeader } from "../components/NodeHeader";
+import { PdfFillEditor } from "./PdfFillEditor";
+import type { PdfFillNode as PdfFillNodeType } from "./types";
+
+function PdfFillNode({ id, data }: NodeProps<PdfFillNodeType>) {
+ const { editable, label } = data;
+ const { blockLabel: urlBlockLabel } = useParams();
+ const { data: workflowRun } = useWorkflowRunQuery();
+ const workflowRunIsRunningOrQueued =
+ workflowRun && statusIsRunningOrQueued(workflowRun);
+ const thisBlockIsTargetted =
+ urlBlockLabel !== undefined && urlBlockLabel === label;
+ const thisBlockIsPlaying =
+ workflowRunIsRunningOrQueued && thisBlockIsTargetted;
+ const recordingStore = useRecordingStore();
+ const { open } = useCollapseContext();
+
+ return (
+ <div
+ className={cn({
+ "pointer-events-none opacity-50": recordingStore.isRecording,
+ })}
+ >
+ <Handle
+ type="source"
+ position={Position.Bottom}
+ id="a"
+ className="opacity-0"
+ />
+ <Handle
+ type="target"
+ position={Position.Top}
+ id="b"
+ className="opacity-0"
+ />
+ <div
+ className={cn(
+ "w-[30rem] space-y-4 rounded-lg bg-slate-elevation3 px-6 py-4 transition-shadow motion-reduce:transition-none",
+ open ? "shadow-md" : "shadow-sm",
+ {
+ "pointer-events-none": thisBlockIsPlaying,
+ "bg-slate-950 outline outline-2 outline-slate-300":
+ thisBlockIsTargetted,
+ },
+ )}
+ >
+ <NodeHeader
+ blockLabel={label}
+ editable={editable}
+ nodeId={id}
+ totpIdentifier={null}
+ totpUrl={null}
+ type="pdf_fill"
+ />
+ <NodeBody>
+ <BuildModeOnly>
+ <PdfFillEditor blockId={id} />
+ </BuildModeOnly>
+ </NodeBody>
+ </div>
+ </div>
+ );
+}
+
+export { PdfFillNode };
diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/PdfFillNode/index.ts b/skyvern-frontend/src/routes/workflows/editor/nodes/PdfFillNode/index.ts
new file mode 100644
index 000000000..bedd9c4ae
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/PdfFillNode/index.ts
@@ -0,0 +1,2 @@
+export { PdfFillNode } from "./PdfFillNode";
+export type { PdfFillNode as PdfFillNodeType } from "./types";
diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/PdfFillNode/types.ts b/skyvern-frontend/src/routes/workflows/editor/nodes/PdfFillNode/types.ts
new file mode 100644
index 000000000..29d8637c4
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/PdfFillNode/types.ts
@@ -0,0 +1,30 @@
+import type { Node } from "@xyflow/react";
+import { debuggableWorkflowBlockTypes } from "@/routes/workflows/types/workflowTypes";
+import { NodeBaseData } from "../types";
+
+export type PdfFillNodeData = NodeBaseData & {
+ fileUrl: string;
+ prompt: string;
+ payload: string;
+ llmKey: string;
+ parameterKeys: Array<string>;
+};
+
+export type PdfFillNode = Node<PdfFillNodeData, "pdfFill">;
+
+export const pdfFillNodeDefaultData: PdfFillNodeData = {
+ debuggable: debuggableWorkflowBlockTypes.has("pdf_fill"),
+ label: "",
+ continueOnFailure: false,
+ editable: true,
+ model: null,
+ fileUrl: "",
+ prompt: "",
+ payload: "{}",
+ llmKey: "",
+ parameterKeys: [],
+};
+
+export function isPdfFillNode(node: Node): node is PdfFillNode {
+ return node.type === "pdfFill";
+}
diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/PdfFillNode/validate.ts b/skyvern-frontend/src/routes/workflows/editor/nodes/PdfFillNode/validate.ts
new file mode 100644
index 000000000..e4a5f125b
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/PdfFillNode/validate.ts
@@ -0,0 +1,26 @@
+import { validateJson } from "../HttpRequestNode/httpValidation";
+import type { PdfFillNode } from "./types";
+
+export function validatePdfFillNode(node: PdfFillNode): Array<string> {
+ const errors: Array<string> = [];
+ if (!node.data.fileUrl.trim()) {
+ errors.push(`${node.data.label}: File URL is required.`);
+ }
+ if (!node.data.prompt.trim()) {
+ errors.push(`${node.data.label}: Prompt is required.`);
+ }
+ // Payloads with any Jinja span are templated server-side before parsing, including inline
+ // expressions for non-string values (e.g. {"items": {{ applicant_list }}}). Those aren't valid
+ // JSON until rendered, so only JSON-validate JSON-shaped payloads that contain no {{ ... }} spans.
+ const trimmedPayload = node.data.payload.trim();
+ const containsJinja = /\{\{.*?\}\}/s.test(trimmedPayload);
+ const looksLikeJson =
+ trimmedPayload.startsWith("{") || trimmedPayload.startsWith("[");
+ if (looksLikeJson && !containsJinja) {
+ const payloadResult = validateJson(node.data.payload);
+ if (!payloadResult.valid && payloadResult.message) {
+ errors.push(`${node.data.label}: Payload - ${payloadResult.message}`);
+ }
+ }
+ return errors;
+}
diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/WorkflowBlockIcon.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/WorkflowBlockIcon.tsx
index 1b8e6f3a5..9e19fa414 100644
--- a/skyvern-frontend/src/routes/workflows/editor/nodes/WorkflowBlockIcon.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/WorkflowBlockIcon.tsx
@@ -88,6 +88,9 @@ function WorkflowBlockIcon({ workflowBlockType, className }: Props) {
case "pdf_parser": {
return <FileTextIcon className={className} />;
}
+ case "pdf_fill": {
+ return <FileTextIcon className={className} />;
+ }
case "goto_url": {
return <ExternalLinkIcon className={className} />;
}
diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/blockTypeFromNode.test.ts b/skyvern-frontend/src/routes/workflows/editor/nodes/blockTypeFromNode.test.ts
index a22f19c6e..36aca72f0 100644
--- a/skyvern-frontend/src/routes/workflows/editor/nodes/blockTypeFromNode.test.ts
+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/blockTypeFromNode.test.ts
@@ -18,6 +18,10 @@ describe("blockTypeFromNode", () => {
);
});
+ it("maps pdfFill to pdf_fill", () => {
+ expect(blockTypeFromNode({ type: "pdfFill" })).toBe("pdf_fill");
+ });
+
it("maps url to goto_url", () => {
expect(blockTypeFromNode({ type: "url" })).toBe("goto_url");
});
diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/blockTypeFromNode.ts b/skyvern-frontend/src/routes/workflows/editor/nodes/blockTypeFromNode.ts
index d86ef3c7a..5f2f81de9 100644
--- a/skyvern-frontend/src/routes/workflows/editor/nodes/blockTypeFromNode.ts
+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/blockTypeFromNode.ts
@@ -28,6 +28,7 @@ const REACT_FLOW_TYPE_TO_BLOCK_TYPE: Record<string, string> = {
workflowTrigger: "workflow_trigger",
googleSheetsRead: "google_sheets_read",
googleSheetsWrite: "google_sheets_write",
+ pdfFill: "pdf_fill",
};
type Loopish = { type?: string; data?: Partial<LoopNodeData> };
diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/index.ts b/skyvern-frontend/src/routes/workflows/editor/nodes/index.ts
index 35bc15cc4..86871530d 100644
--- a/skyvern-frontend/src/routes/workflows/editor/nodes/index.ts
+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/index.ts
@@ -56,6 +56,8 @@ import { GoogleSheetsReadNode } from "./GoogleSheetsReadNode/types";
import { GoogleSheetsReadNode as GoogleSheetsReadNodeComponent } from "./GoogleSheetsReadNode/GoogleSheetsReadNode";
import { GoogleSheetsWriteNode } from "./GoogleSheetsWriteNode/types";
import { GoogleSheetsWriteNode as GoogleSheetsWriteNodeComponent } from "./GoogleSheetsWriteNode/GoogleSheetsWriteNode";
+import { PdfFillNode } from "./PdfFillNode/types";
+import { PdfFillNode as PdfFillNodeComponent } from "./PdfFillNode/PdfFillNode";
import { withSortableBlock } from "../sortable/withSortableBlock";
import { withCollapsible } from "../collapse/withCollapsible";
import { withSelectableBlock } from "../selection/withSelectableBlock";
@@ -88,7 +90,8 @@ export type WorkflowBlockNode =
| PrintPageNode
| WorkflowTriggerNode
| GoogleSheetsReadNode
- | GoogleSheetsWriteNode;
+ | GoogleSheetsWriteNode
+ | PdfFillNode;
export function isUtilityNode(node: AppNode): node is UtilityNode {
return node.type === "nodeAdder" || node.type === "start";
@@ -150,4 +153,5 @@ export const nodeTypes = {
workflowTrigger: wrapBlock(WorkflowTriggerNodeComponent),
googleSheetsRead: wrapBlock(GoogleSheetsReadNodeComponent),
googleSheetsWrite: wrapBlock(GoogleSheetsWriteNodeComponent),
+ pdfFill: wrapBlock(PdfFillNodeComponent),
} as const;
diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/types.ts b/skyvern-frontend/src/routes/workflows/editor/nodes/types.ts
index eb9641344..531088c90 100644
--- a/skyvern-frontend/src/routes/workflows/editor/nodes/types.ts
+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/types.ts
@@ -74,4 +74,5 @@ export const workflowBlockTitle: {
workflow_trigger: "Agent Trigger",
google_sheets_read: "Google Sheets Read",
google_sheets_write: "Google Sheets Write",
+ pdf_fill: "PDF Fill",
};
diff --git a/skyvern-frontend/src/routes/workflows/editor/nodes/wrap.test.tsx b/skyvern-frontend/src/routes/workflows/editor/nodes/wrap.test.tsx
index cf547a355..d5152d438 100644
--- a/skyvern-frontend/src/routes/workflows/editor/nodes/wrap.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/nodes/wrap.test.tsx
@@ -43,6 +43,7 @@ describe("nodeTypes composition order", () => {
"workflowTrigger",
"googleSheetsRead",
"googleSheetsWrite",
+ "pdfFill",
]),
);
});
diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm.test.tsx b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm.test.tsx
index 02f1035cc..e02b899e3 100644
--- a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm.test.tsx
@@ -78,7 +78,7 @@ describe("BLOCK_FORMS dispatcher", () => {
}
});
- test("contains the 26 expected node.type keys", () => {
+ test("contains the 27 expected node.type keys", () => {
expect(new Set(BLOCK_FORM_KEYS)).toEqual(
new Set([
"task",
@@ -107,9 +107,10 @@ describe("BLOCK_FORMS dispatcher", () => {
"workflowTrigger",
"googleSheetsRead",
"googleSheetsWrite",
+ "pdfFill",
]),
);
- expect(BLOCK_FORM_KEYS).toHaveLength(26);
+ expect(BLOCK_FORM_KEYS).toHaveLength(27);
});
test("conditional routes to the sidebar placeholder (canvas tile owns BranchesEditor)", () => {
diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm.tsx b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm.tsx
index 69ac9296d..4af872d84 100644
--- a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm.tsx
@@ -20,6 +20,7 @@ import { LoopBlockForm } from "./BlockConfigForm/LoopBlockForm";
import { NavigationBlockForm } from "./BlockConfigForm/NavigationBlockForm";
import { PDFParserBlockForm } from "./BlockConfigForm/PDFParserBlockForm";
import { PrintPageBlockForm } from "./BlockConfigForm/PrintPageBlockForm";
+import { PdfFillBlockForm } from "./BlockConfigForm/PdfFillBlockForm";
import { SendEmailBlockForm } from "./BlockConfigForm/SendEmailBlockForm";
import { TaskBlockForm } from "./BlockConfigForm/TaskBlockForm";
import { Taskv2BlockForm } from "./BlockConfigForm/Taskv2BlockForm";
@@ -73,6 +74,7 @@ const BLOCK_FORMS: Record<WorkflowBlockNodeType, BlockFormComponent> = {
url: URLBlockForm,
http_request: HttpRequestBlockForm,
printPage: PrintPageBlockForm,
+ pdfFill: PdfFillBlockForm,
workflowTrigger: WorkflowTriggerBlockForm,
googleSheetsRead: GoogleSheetsReadBlockForm,
googleSheetsWrite: GoogleSheetsWriteBlockForm,
diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/PdfFillBlockForm.test.tsx b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/PdfFillBlockForm.test.tsx
new file mode 100644
index 000000000..8157ad71e
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/PdfFillBlockForm.test.tsx
@@ -0,0 +1,267 @@
+// @vitest-environment jsdom
+
+import {
+ act,
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+} from "@testing-library/react";
+import type { ReactNode } from "react";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+
+import type { PdfFillNode } from "../../nodes/PdfFillNode/types";
+
+const mockNodes = new Map<
+ string,
+ { id: string; type: string; data?: Record<string, unknown> } | undefined
+>();
+const updateNodeData = vi.fn();
+
+vi.mock("@xyflow/react", async () => {
+ const actual =
+ await vi.importActual<typeof import("@xyflow/react")>("@xyflow/react");
+ return {
+ ...actual,
+ useReactFlow: () => ({
+ getNode: (id: string) => mockNodes.get(id),
+ updateNodeData,
+ }),
+ useNodesData: (id: string) => {
+ const node = mockNodes.get(id);
+ return node ? { id: node.id, type: node.type, data: node.data } : null;
+ },
+ useNodes: () => Array.from(mockNodes.values()),
+ useEdges: () => [],
+ };
+});
+
+vi.mock("../../workflowEditorUtils", () => ({
+ getAvailableOutputParameterKeys: () => [],
+ isNodeInsideForLoop: () => false,
+ getParentLoopSkipsOnFail: () => false,
+}));
+
+vi.mock("@/components/HelpTooltip", () => ({
+ HelpTooltip: () => <span data-testid="help-tooltip" />,
+}));
+
+vi.mock("@/components/ModelSelector", () => ({
+ ModelSelector: (props: {
+ value: unknown;
+ onChange: (value: unknown) => void;
+ }) => (
+ <button
+ data-testid="model-selector"
+ onClick={() => props.onChange({ model_name: "gpt-test" })}
+ />
+ ),
+}));
+
+vi.mock("@/components/WorkflowBlockInput", () => ({
+ WorkflowBlockInput: (props: {
+ value: string;
+ onChange: (value: string) => void;
+ }) => (
+ <input
+ data-testid="workflow-block-input"
+ value={props.value}
+ onChange={(event) => props.onChange(event.target.value)}
+ />
+ ),
+}));
+
+vi.mock("@/components/WorkflowBlockInputTextarea", () => ({
+ WorkflowBlockInputTextarea: (props: {
+ value: string;
+ onChange: (value: string) => void;
+ placeholder?: string;
+ }) => (
+ <textarea
+ data-testid={`wbi-ph-${props.placeholder ?? ""}`}
+ value={props.value}
+ onChange={(event) => props.onChange(event.target.value)}
+ />
+ ),
+}));
+
+vi.mock("@/routes/workflows/components/CodeEditor", () => ({
+ CodeEditor: (props: { value: string; onChange: (value: string) => void }) => (
+ <textarea
+ data-testid="code-editor"
+ value={props.value}
+ onChange={(event) => props.onChange(event.target.value)}
+ />
+ ),
+}));
+
+vi.mock("../../nodes/HttpRequestNode/HttpUtils", () => ({
+ JsonValidator: ({ value }: { value: string }) => (
+ <div data-testid="json-validator" data-value={value} />
+ ),
+}));
+
+vi.mock("../../nodes/TaskNode/ParametersMultiSelect", () => ({
+ ParametersMultiSelect: (props: {
+ parameters: Array<string>;
+ onParametersChange: (next: Array<string>) => void;
+ }) => (
+ <button
+ data-testid="parameters-change"
+ onClick={() => props.onParametersChange(["param_a"])}
+ />
+ ),
+}));
+
+vi.mock("../../nodes/WorkflowBlockParameterSelect", () => ({
+ WorkflowBlockParameterSelect: (props: {
+ onAdd: (parameterKey: string) => void;
+ }) => (
+ <button
+ data-testid="parameter-select-add"
+ onClick={() => props.onAdd("applicant")}
+ />
+ ),
+}));
+
+vi.mock("../../nodes/IgnoreWorkflowSystemPrompt", () => ({
+ IgnoreWorkflowSystemPrompt: (props: {
+ onIgnoreWorkflowSystemPromptChange: (value: boolean) => void;
+ }) => (
+ <button
+ data-testid="ignore-workflow-system-prompt"
+ onClick={() => props.onIgnoreWorkflowSystemPromptChange(true)}
+ />
+ ),
+}));
+
+vi.mock("@/components/ui/accordion", () => {
+ const Pass = ({ children }: { children?: ReactNode }) => <>{children}</>;
+ return {
+ Accordion: Pass,
+ AccordionItem: Pass,
+ AccordionTrigger: ({ children }: { children?: ReactNode }) => (
+ <button data-testid="accordion-trigger">{children}</button>
+ ),
+ AccordionContent: Pass,
+ };
+});
+
+vi.mock("@/components/ui/popover", () => {
+ const Pass = ({ children }: { children?: ReactNode }) => <>{children}</>;
+ return {
+ Popover: Pass,
+ PopoverTrigger: Pass,
+ PopoverContent: Pass,
+ };
+});
+
+import { useSidebarSaveStateStore } from "@/store/SidebarSaveStateStore";
+import { usePendingCommitsStore } from "@/store/PendingCommitsStore";
+import { PdfFillBlockForm } from "./PdfFillBlockForm";
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ mockNodes.clear();
+ updateNodeData.mockReset();
+ usePendingCommitsStore.setState({ commits: {} });
+ useSidebarSaveStateStore.getState().reset();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ cleanup();
+});
+
+function setPdfFillNode(
+ id: string,
+ overrides: Partial<PdfFillNode["data"]> = {},
+) {
+ mockNodes.set(id, {
+ id,
+ type: "pdfFill",
+ data: {
+ debuggable: true,
+ label: "pdf_fill_1",
+ continueOnFailure: false,
+ editable: true,
+ model: null,
+ fileUrl: "",
+ prompt: "",
+ payload: "{}",
+ llmKey: "",
+ parameterKeys: [],
+ ...overrides,
+ },
+ });
+}
+
+describe("PdfFillBlockForm", () => {
+ test("returns null for missing node", () => {
+ const { container } = render(<PdfFillBlockForm blockId="missing" />);
+ expect(container.firstChild).toBeNull();
+ });
+
+ test("returns null for wrong node type", () => {
+ mockNodes.set("p1", { id: "p1", type: "task", data: {} });
+ const { container } = render(<PdfFillBlockForm blockId="p1" />);
+ expect(container.firstChild).toBeNull();
+ });
+
+ test("renders core PDF fill controls", () => {
+ setPdfFillNode("p1");
+ render(<PdfFillBlockForm blockId="p1" />);
+
+ expect(screen.getByTestId("pdf-fill-block-form")).toBeDefined();
+ expect(screen.getByText("File URL")).toBeDefined();
+ expect(screen.getByText("Prompt")).toBeDefined();
+ expect(screen.getByText("Payload")).toBeDefined();
+ expect(screen.queryByText("API Key")).toBeNull();
+ });
+
+ test("editing file URL, prompt, and payload propagates", () => {
+ setPdfFillNode("p1");
+ render(<PdfFillBlockForm blockId="p1" />);
+
+ const inputs = screen.getAllByTestId("workflow-block-input");
+ expect(inputs[0]).toBeDefined();
+ fireEvent.change(inputs[0]!, { target: { value: "{{ pdf_output }}" } });
+ fireEvent.change(
+ screen.getByTestId("wbi-ph-Fill the form using the payload."),
+ { target: { value: "Fill the applicant form" } },
+ );
+ fireEvent.change(screen.getByTestId("code-editor"), {
+ target: { value: '{"name":"Jane"}' },
+ });
+
+ expect(updateNodeData).toHaveBeenCalledWith("p1", {
+ fileUrl: "{{ pdf_output }}",
+ });
+ expect(updateNodeData).toHaveBeenCalledWith("p1", {
+ prompt: "Fill the applicant form",
+ });
+ expect(updateNodeData).toHaveBeenCalledWith("p1", {
+ payload: '{"name":"Jane"}',
+ });
+ });
+
+ test("registers/unregisters commit on mount/unmount", () => {
+ setPdfFillNode("p1");
+ const { unmount } = render(<PdfFillBlockForm blockId="p1" />);
+
+ expect(usePendingCommitsStore.getState().commits["p1"]).toBeDefined();
+ unmount();
+ expect(usePendingCommitsStore.getState().commits["p1"]).toBeUndefined();
+ });
+
+ test("flush via PendingCommitsStore returns true", () => {
+ setPdfFillNode("p1");
+ render(<PdfFillBlockForm blockId="p1" />);
+
+ let ok = false;
+ act(() => {
+ ok = usePendingCommitsStore.getState().flush("p1");
+ });
+ expect(ok).toBe(true);
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/PdfFillBlockForm.tsx b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/PdfFillBlockForm.tsx
new file mode 100644
index 000000000..0b62f7b6e
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/PdfFillBlockForm.tsx
@@ -0,0 +1,76 @@
+import { useReactFlow } from "@xyflow/react";
+import { useEffect, useMemo } from "react";
+
+import { usePendingCommitsStore } from "@/store/PendingCommitsStore";
+
+import { isWorkflowBlockNode, type AppNode } from "../../nodes";
+import { PdfFillEditor } from "../../nodes/PdfFillNode/PdfFillEditor";
+import { isPdfFillNode, type PdfFillNode } from "../../nodes/PdfFillNode/types";
+import { useDebouncedSidebarSave } from "../useDebouncedSidebarSave";
+
+function PdfFillBlockForm({ blockId }: { blockId: string }) {
+ const { getNode } = useReactFlow<AppNode>();
+ const node = getNode(blockId);
+ if (!node || !isWorkflowBlockNode(node) || !isPdfFillNode(node)) {
+ return null;
+ }
+ return <PdfFillBlockFormBody blockId={blockId} node={node as PdfFillNode} />;
+}
+
+function PdfFillBlockFormBody({
+ blockId,
+ node,
+}: {
+ blockId: string;
+ node: PdfFillNode;
+}) {
+ const {
+ fileUrl,
+ prompt,
+ payload,
+ llmKey,
+ parameterKeys,
+ model,
+ ignoreWorkflowSystemPrompt,
+ continueOnFailure,
+ } = node.data;
+
+ const value = useMemo(
+ () => ({
+ fileUrl,
+ prompt,
+ payload,
+ llmKey,
+ parameterKeys,
+ model,
+ ignoreWorkflowSystemPrompt,
+ continueOnFailure,
+ }),
+ [
+ fileUrl,
+ prompt,
+ payload,
+ llmKey,
+ parameterKeys,
+ model,
+ ignoreWorkflowSystemPrompt,
+ continueOnFailure,
+ ],
+ );
+ const { commit } = useDebouncedSidebarSave({
+ blockId,
+ value,
+ });
+
+ useEffect(() => {
+ const store = usePendingCommitsStore.getState();
+ store.register(blockId, commit);
+ return () => {
+ store.unregister(blockId);
+ };
+ }, [blockId, commit]);
+
+ return <PdfFillEditor blockId={blockId} />;
+}
+
+export { PdfFillBlockForm };
diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigSidebar.tsx b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigSidebar.tsx
index 870ac29b0..7eb0d7513 100644
--- a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigSidebar.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigSidebar.tsx
@@ -65,6 +65,7 @@ const NODE_TYPE_TO_BLOCK_TYPE: Record<
workflowTrigger: "workflow_trigger",
googleSheetsRead: "google_sheets_read",
googleSheetsWrite: "google_sheets_write",
+ pdfFill: "pdf_fill",
};
function getBlockTypeFromNode(node: AppNode): WorkflowBlockType | null {
diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/WorkflowComparisonPanel.tsx b/skyvern-frontend/src/routes/workflows/editor/panels/WorkflowComparisonPanel.tsx
index 20f76541b..6ab566a14 100644
--- a/skyvern-frontend/src/routes/workflows/editor/panels/WorkflowComparisonPanel.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/panels/WorkflowComparisonPanel.tsx
@@ -59,6 +59,7 @@ const BLOCK_TYPE_TO_NODE_TYPE: Record<string, string> = {
file_upload: "fileUpload",
goto_url: "url",
http_request: "http_request",
+ pdf_fill: "pdfFill",
google_sheets_read: "googleSheetsRead",
google_sheets_write: "googleSheetsWrite",
};
diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/WorkflowNodeLibraryPanel.tsx b/skyvern-frontend/src/routes/workflows/editor/panels/WorkflowNodeLibraryPanel.tsx
index 5cf658624..2e25e4057 100644
--- a/skyvern-frontend/src/routes/workflows/editor/panels/WorkflowNodeLibraryPanel.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/panels/WorkflowNodeLibraryPanel.tsx
@@ -258,6 +258,17 @@ const nodeLibraryItems: Array<{
title: "Print Page Block",
description: "Print current page to PDF",
},
+ {
+ nodeType: "pdfFill",
+ icon: (
+ <WorkflowBlockIcon
+ workflowBlockType={WorkflowBlockTypes.PDFFill}
+ className="size-6"
+ />
+ ),
+ title: "PDF Fill Block",
+ description: "Fill a PDF form",
+ },
{
nodeType: "workflowTrigger",
icon: (
diff --git a/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.ts b/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.ts
index 4d5ec494f..255db9f3a 100644
--- a/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.ts
+++ b/skyvern-frontend/src/routes/workflows/editor/workflowEditorUtils.ts
@@ -54,6 +54,7 @@ import {
WorkflowTriggerBlockYAML,
GoogleSheetsReadBlockYAML,
GoogleSheetsWriteBlockYAML,
+ PdfFillBlockYAML,
} from "../types/workflowYamlTypes";
import {
EMAIL_BLOCK_SENDER,
@@ -157,6 +158,11 @@ import {
isGoogleSheetsWriteNode,
} from "./nodes/GoogleSheetsWriteNode/types";
import { validateGoogleSheetsWriteNode } from "./nodes/GoogleSheetsWriteNode/validate";
+import {
+ isPdfFillNode,
+ pdfFillNodeDefaultData,
+} from "./nodes/PdfFillNode/types";
+import { validatePdfFillNode } from "./nodes/PdfFillNode/validate";
import {
containsJinjaReference,
getAffectedBlocks,
@@ -1105,6 +1111,24 @@ function convertToNode(
},
};
}
+ case "pdf_fill": {
+ return {
+ ...identifiers,
+ ...common,
+ type: "pdfFill",
+ data: {
+ ...commonData,
+ fileUrl: block.file_url ?? "",
+ prompt: block.prompt ?? "",
+ payload:
+ typeof block.payload === "string"
+ ? block.payload
+ : JSON.stringify(block.payload || {}, null, 2),
+ llmKey: block.llm_key ?? "",
+ parameterKeys: block.parameters.map((p) => p.key),
+ },
+ };
+ }
case "workflow_trigger": {
return {
...identifiers,
@@ -2509,6 +2533,17 @@ function createNode(
},
};
}
+ case "pdfFill": {
+ return {
+ ...identifiers,
+ ...common,
+ type: "pdfFill",
+ data: {
+ ...pdfFillNodeDefaultData,
+ label,
+ },
+ };
+ }
case "workflowTrigger": {
return {
...identifiers,
@@ -2580,6 +2615,19 @@ function JSONSafeOrString(
}
}
+function JSONSafeOrStringAllowArrays(
+ json: string,
+): Record<string, unknown> | Array<unknown> | string | null {
+ if (!json) {
+ return null;
+ }
+ try {
+ return JSON.parse(json);
+ } catch {
+ return json;
+ }
+}
+
function serializeLoopNodeToYAML(
node: LoopNode,
loopChildren: Array<BlockYAML>,
@@ -3061,6 +3109,17 @@ function getWorkflowBlock(
parameter_keys: node.data.parameterKeys,
};
}
+ case "pdfFill": {
+ return {
+ ...base,
+ block_type: "pdf_fill",
+ file_url: node.data.fileUrl,
+ prompt: node.data.prompt,
+ payload: JSONSafeOrStringAllowArrays(node.data.payload),
+ llm_key: node.data.llmKey || null,
+ parameter_keys: node.data.parameterKeys,
+ };
+ }
case "workflowTrigger": {
const parsedPayload = JSONParseSafe(node.data.payload) as Record<
string,
@@ -4405,6 +4464,18 @@ function convertBlocksToBlockYAML(
};
return blockYaml;
}
+ case "pdf_fill": {
+ const blockYaml: PdfFillBlockYAML = {
+ ...base,
+ block_type: "pdf_fill",
+ file_url: block.file_url,
+ prompt: block.prompt,
+ payload: block.payload,
+ llm_key: block.llm_key,
+ parameter_keys: block.parameters.map((p) => p.key),
+ };
+ return blockYaml;
+ }
case "workflow_trigger": {
const blockYaml: WorkflowTriggerBlockYAML = {
...base,
@@ -4719,6 +4790,10 @@ function getWorkflowErrors(nodes: Array<AppNode>): Array<string> {
.filter(isGoogleSheetsWriteNode)
.forEach((node) => errors.push(...validateGoogleSheetsWriteNode(node)));
+ nodes
+ .filter(isPdfFillNode)
+ .forEach((node) => errors.push(...validatePdfFillNode(node)));
+
return errors;
}
diff --git a/skyvern-frontend/src/routes/workflows/types/workflowTypes.ts b/skyvern-frontend/src/routes/workflows/types/workflowTypes.ts
index 12165c557..505f89c1b 100644
--- a/skyvern-frontend/src/routes/workflows/types/workflowTypes.ts
+++ b/skyvern-frontend/src/routes/workflows/types/workflowTypes.ts
@@ -216,7 +216,8 @@ export type WorkflowBlock =
| PrintPageBlock
| WorkflowTriggerBlock
| GoogleSheetsReadBlock
- | GoogleSheetsWriteBlock;
+ | GoogleSheetsWriteBlock
+ | PdfFillBlock;
export const WorkflowBlockTypes = {
Task: "task",
@@ -246,6 +247,7 @@ export const WorkflowBlockTypes = {
WorkflowTrigger: "workflow_trigger",
GoogleSheetsRead: "google_sheets_read",
GoogleSheetsWrite: "google_sheets_write",
+ PDFFill: "pdf_fill",
} as const;
// all of them
@@ -624,6 +626,15 @@ export type GoogleSheetsWriteBlock = WorkflowBlockBase & {
parameters: Array<WorkflowParameter>;
};
+export type PdfFillBlock = WorkflowBlockBase & {
+ block_type: "pdf_fill";
+ file_url: string;
+ prompt: string;
+ payload: Record<string, unknown> | Array<unknown> | string | null;
+ llm_key: string | null;
+ parameters: Array<WorkflowParameter>;
+};
+
export type WorkflowDefinition = {
version?: number | null;
parameters: Array<Parameter>;
diff --git a/skyvern-frontend/src/routes/workflows/types/workflowYamlTypes.ts b/skyvern-frontend/src/routes/workflows/types/workflowYamlTypes.ts
index 02e856261..c50c4be00 100644
--- a/skyvern-frontend/src/routes/workflows/types/workflowYamlTypes.ts
+++ b/skyvern-frontend/src/routes/workflows/types/workflowYamlTypes.ts
@@ -155,7 +155,8 @@ export type BlockYAML =
| PrintPageBlockYAML
| WorkflowTriggerBlockYAML
| GoogleSheetsReadBlockYAML
- | GoogleSheetsWriteBlockYAML;
+ | GoogleSheetsWriteBlockYAML
+ | PdfFillBlockYAML;
export type BlockYAMLBase = {
block_type: WorkflowBlockType;
@@ -471,3 +472,12 @@ export type GoogleSheetsWriteBlockYAML = BlockYAMLBase & {
create_sheet_if_missing?: boolean;
parameter_keys?: Array<string> | null;
};
+
+export type PdfFillBlockYAML = BlockYAMLBase & {
+ block_type: "pdf_fill";
+ file_url: string;
+ prompt: string;
+ payload: Record<string, unknown> | Array<unknown> | string | null;
+ llm_key?: string | null;
+ parameter_keys?: Array<string> | null;
+};
diff --git a/skyvern/cli/mcp_tools/blocks.py b/skyvern/cli/mcp_tools/blocks.py
index 9e1c6d4b6..24ac90773 100644
--- a/skyvern/cli/mcp_tools/blocks.py
+++ b/skyvern/cli/mcp_tools/blocks.py
@@ -34,6 +34,7 @@ from skyvern.schemas.workflows import (
HumanInteractionBlockYAML,
LoginBlockYAML,
NavigationBlockYAML,
+ PdfFillBlockYAML,
PDFParserBlockYAML,
PrintPageBlockYAML,
SendEmailBlockYAML,
@@ -81,6 +82,7 @@ BLOCK_TYPE_MAP: dict[str, type[BlockYAML]] = {
BlockType.PDF_PARSER.value: PDFParserBlockYAML,
BlockType.HUMAN_INTERACTION.value: HumanInteractionBlockYAML,
BlockType.PRINT_PAGE.value: PrintPageBlockYAML,
+ BlockType.PDF_FILL.value: PdfFillBlockYAML,
BlockType.WORKFLOW_TRIGGER.value: WorkflowTriggerBlockYAML,
BlockType.GOOGLE_SHEETS_READ.value: GoogleSheetsReadBlockYAML,
BlockType.GOOGLE_SHEETS_WRITE.value: GoogleSheetsWriteBlockYAML,
@@ -113,6 +115,7 @@ BLOCK_SUMMARIES: dict[str, str] = {
"pdf_parser": "Extract structured data from a PDF document",
"human_interaction": "Pause workflow for human approval via email",
"print_page": "Print the current page to PDF",
+ "pdf_fill": "Fill a PDF form (AcroForm fields, or flat PDFs via OCR overlay) from a prompt and structured payload",
"workflow_trigger": "Trigger another workflow by permanent ID, with optional payload and wait-for-completion",
"google_sheets_read": "Read rows from a Google Sheet as structured data (list of dicts)",
"google_sheets_write": "Write rows to a Google Sheet (append new rows or update existing cells)",
@@ -247,6 +250,14 @@ BLOCK_EXAMPLES: dict[str, dict[str, Any]] = {
"payload": {"url": "{{ some_parameter }}"},
"wait_for_completion": True,
},
+ "pdf_fill": {
+ "block_type": "pdf_fill",
+ "label": "fill_application_pdf",
+ "file_url": "{{ source_pdf_output }}",
+ "prompt": "Fill the application using the applicant payload.",
+ "payload": "{{ applicant | json }}",
+ "parameter_keys": ["source_pdf_output", "applicant"],
+ },
"google_sheets_read": {
"block_type": "google_sheets_read",
"label": "read_sheet_data",
diff --git a/skyvern/forge/prompts/skyvern/pdf-fill-field-mapping.j2 b/skyvern/forge/prompts/skyvern/pdf-fill-field-mapping.j2
new file mode 100644
index 000000000..4ab54b236
--- /dev/null
+++ b/skyvern/forge/prompts/skyvern/pdf-fill-field-mapping.j2
@@ -0,0 +1,24 @@
+You are mapping user instructions and structured payload data to fields in a fillable PDF form.
+
+Return only strict JSON with this exact top-level shape:
+{"fields": {"<field_name>": <value>}, "thought": "..."}
+
+Rules:
+- Only include fields you can confidently fill from the user instructions and payload.
+- Field names must exactly match one of the PDF field names.
+- Checkbox values must be booleans.
+- Radio and choice values must exactly match one of the field's allowed values.
+- Do not include explanatory text outside the JSON object.
+
+PDF field inventory:
+```json
+{{ field_inventory | tojson }}
+```
+
+User fill instructions:
+{{ user_prompt | untrusted }}
+
+Structured payload:
+```json
+{{ payload_json | untrusted }}
+```
diff --git a/skyvern/forge/prompts/skyvern/pdf-fill-flat-placement.j2 b/skyvern/forge/prompts/skyvern/pdf-fill-flat-placement.j2
new file mode 100644
index 000000000..99c9d5008
--- /dev/null
+++ b/skyvern/forge/prompts/skyvern/pdf-fill-flat-placement.j2
@@ -0,0 +1,26 @@
+You are filling a NON-INTERACTIVE (flat) PDF form by placing text values next to printed labels.
+
+Each anchor below is a line of text detected on the form via OCR. Coordinates are pixels with (0,0) at the top-left of each page image; page_width_px and page_height_px give the page bounds.
+
+Return only strict JSON with this exact top-level shape:
+{"placements": [{"anchor_id": <int>, "value": "<text>", "position": "right" | "below"}], "thought": "..."}
+
+Rules:
+- Only place values you can confidently derive from the user instructions and payload.
+- anchor_id must be the id of the detected label line the value belongs to.
+- Use "right" to put the value on the same line after the label (typical for "Label:" lines with empty space after them). Use "below" to put the value underneath the label inside its box.
+- Each value must be a plain single-line string. Do not invent values that are not in the payload or instructions.
+- Do not include explanatory text outside the JSON object.
+
+Detected anchors:
+```json
+{{ anchors | tojson }}
+```
+
+User fill instructions:
+{{ user_prompt | untrusted }}
+
+Structured payload:
+```json
+{{ payload_json | untrusted }}
+```
diff --git a/skyvern/forge/sdk/workflow/models/_jinja.py b/skyvern/forge/sdk/workflow/models/_jinja.py
index 870920bba..1b8ce78f4 100644
--- a/skyvern/forge/sdk/workflow/models/_jinja.py
+++ b/skyvern/forge/sdk/workflow/models/_jinja.py
@@ -3,12 +3,13 @@
from __future__ import annotations
import json
-from typing import Any
+from typing import Any, Callable, cast
from jinja2 import StrictUndefined
from jinja2.sandbox import SandboxedEnvironment
from skyvern.config import settings
+from skyvern.forge.sdk.workflow.exceptions import FailedToFormatJinjaStyleParameter
# Sentinel marker for native JSON type injection via | json filter.
_JSON_TYPE_MARKER = "__SKYVERN_RAW_JSON__"
@@ -36,6 +37,37 @@ def _json_finalize(value: Any) -> Any:
return value
+def render_templates_in_json_value(value: object, render_string: Callable[[str], str]) -> object:
+ """Recursively render Jinja templates in nested JSON-like structures, honoring the
+ `{{ expr | json }}` filter for type-preserving JSON injection."""
+ if isinstance(value, str):
+ rendered = render_string(value)
+ if rendered.startswith(_JSON_TYPE_MARKER) and rendered.endswith(_JSON_TYPE_MARKER):
+ json_str = rendered[len(_JSON_TYPE_MARKER) : -len(_JSON_TYPE_MARKER)]
+ try:
+ return json.loads(json_str)
+ except json.JSONDecodeError:
+ raise FailedToFormatJinjaStyleParameter(value, f"Raw JSON filter produced invalid JSON: {json_str}")
+ if _JSON_TYPE_MARKER in rendered:
+ raise FailedToFormatJinjaStyleParameter(
+ value,
+ "The '| json' filter can only be used for complete value replacement. "
+ "It cannot be combined with other text (e.g., 'prefix-{{ val | json }}'). "
+ "Remove the surrounding text or remove the '| json' filter.",
+ )
+ return rendered
+ if isinstance(value, list):
+ return [render_templates_in_json_value(item, render_string) for item in value]
+ if isinstance(value, dict):
+ return {
+ cast(str, render_templates_in_json_value(key, render_string)): render_templates_in_json_value(
+ val, render_string
+ )
+ for key, val in value.items()
+ }
+ return value
+
+
jinja_json_finalize_env = SandboxedEnvironment(finalize=_json_finalize)
jinja_json_finalize_env.filters["json"] = _json_type_filter
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.py
index 0cd1a112a..bf3ab2127 100644
--- a/skyvern/forge/sdk/workflow/models/block.py
+++ b/skyvern/forge/sdk/workflow/models/block.py
@@ -120,6 +120,7 @@ from skyvern.forge.sdk.workflow.models._jinja import (
_JSON_TYPE_MARKER,
_json_type_filter,
jinja_json_finalize_strict_env,
+ render_templates_in_json_value,
)
from skyvern.forge.sdk.workflow.models.code_block_recorder import (
CODE_BLOCK_FILENAME,
@@ -266,6 +267,41 @@ TASKV2_TO_BLOCK_STATUS: dict[TaskV2Status, BlockStatus] = {
}
+def extract_file_url_from_block_output(value: Any) -> str | None:
+ """Extract a file URL from block output values that wrap downloaded files."""
+ if isinstance(value, dict):
+ downloaded_files = value.get("downloaded_files")
+ if isinstance(downloaded_files, list) and downloaded_files:
+ first_file = downloaded_files[0]
+ if isinstance(first_file, dict):
+ return first_file.get("url") or first_file.get("file_path") or None
+
+ for key in ("artifact_url", "file_url", "file_path"):
+ extracted = value.get(key)
+ if isinstance(extracted, str) and extracted:
+ return extracted
+ return None
+
+ if isinstance(value, str):
+ try:
+ parsed = json.loads(value)
+ return extract_file_url_from_block_output(parsed)
+ except (json.JSONDecodeError, ValueError):
+ pass
+ try:
+ parsed = ast.literal_eval(value)
+ if isinstance(parsed, dict):
+ return extract_file_url_from_block_output(parsed)
+ except (ValueError, SyntaxError):
+ pass
+ return None
+
+
+def sanitize_filename(filename: str, default: str = "document") -> str:
+ sanitized = re.sub(r'[<>:"/\\|?*]', "_", filename).strip(". ")
+ return sanitized[:200] if sanitized else default
+
+
def _format_payload_path_segment(key: str) -> str:
"""Plain identifiers render as `.key`; anything else (dots, brackets, spaces,
quotes) renders as a bracketed JSON-escaped string so paths stay unambiguous
@@ -5720,26 +5756,7 @@ class FileParserBlock(Block):
- JSON string encoding such a dict
- Python dict-repr string produced by Jinja's default ``str()`` rendering
"""
- if isinstance(value, dict):
- downloaded_files = value.get("downloaded_files")
- if isinstance(downloaded_files, list) and downloaded_files:
- first_file = downloaded_files[0]
- if isinstance(first_file, dict):
- return first_file.get("url") or None
- return None
- if isinstance(value, str):
- try:
- parsed = json.loads(value)
- return FileParserBlock._extract_file_url_from_block_output(parsed)
- except (json.JSONDecodeError, ValueError):
- pass
- try:
- parsed = ast.literal_eval(value)
- if isinstance(parsed, dict):
- return FileParserBlock._extract_file_url_from_block_output(parsed)
- except (ValueError, SyntaxError):
- pass
- return None
+ return extract_file_url_from_block_output(value)
async def execute(
self,
@@ -6671,58 +6688,22 @@ class HttpRequestBlock(Block):
"""Format template parameters in the block fields"""
template_kwargs = {"force_include_secrets": True}
- def _render_templates_in_json(value: object) -> object:
- """
- Recursively render Jinja templates in nested JSON-like structures.
-
- This is required because HTTP request bodies are often deeply nested
- dict/list structures, and templates may appear at any depth.
-
- Supports {{ expr | json }} filter for type-preserving JSON injection.
- """
- if isinstance(value, str):
- rendered = self.format_block_parameter_template_from_workflow_run_context(
- value, workflow_run_context, **template_kwargs
- )
-
- if rendered.startswith(_JSON_TYPE_MARKER) and rendered.endswith(_JSON_TYPE_MARKER):
- json_str = rendered[len(_JSON_TYPE_MARKER) : -len(_JSON_TYPE_MARKER)]
- try:
- return json.loads(json_str)
- except json.JSONDecodeError:
- raise FailedToFormatJinjaStyleParameter(
- value, f"Raw JSON filter produced invalid JSON: {json_str}"
- )
- elif _JSON_TYPE_MARKER in rendered:
- raise FailedToFormatJinjaStyleParameter(
- value,
- "The '| json' filter can only be used for complete value replacement. "
- "It cannot be combined with other text (e.g., 'prefix-{{ val | json }}'). "
- "Remove the surrounding text or remove the '| json' filter.",
- )
- return rendered
- if isinstance(value, list):
- return [_render_templates_in_json(item) for item in value]
- if isinstance(value, dict):
- return {
- cast(str, _render_templates_in_json(key)): _render_templates_in_json(val)
- for key, val in value.items()
- }
- return value
+ def _render_string(value: str) -> str:
+ return self.format_block_parameter_template_from_workflow_run_context(
+ value, workflow_run_context, **template_kwargs
+ )
if self.url:
- self.url = self.format_block_parameter_template_from_workflow_run_context(
- self.url, workflow_run_context, **template_kwargs
- )
+ self.url = _render_string(self.url)
if self.body:
- self.body = cast(dict[str, Any], _render_templates_in_json(self.body))
+ self.body = cast(dict[str, Any], render_templates_in_json_value(self.body, _render_string))
if self.files:
- self.files = cast(dict[str, str], _render_templates_in_json(self.files))
+ self.files = cast(dict[str, str], render_templates_in_json_value(self.files, _render_string))
if self.headers:
- self.headers = cast(dict[str, str], _render_templates_in_json(self.headers))
+ self.headers = cast(dict[str, str], render_templates_in_json_value(self.headers, _render_string))
if self.download_filename:
self.download_filename = self.format_block_parameter_template_from_workflow_run_context(
@@ -7107,9 +7088,7 @@ class PrintPageBlock(Block):
@staticmethod
def _sanitize_filename(filename: str) -> str:
- sanitized = re.sub(r'[<>:"/\\|?*]', "_", filename)
- sanitized = sanitized.strip(". ")
- return sanitized[:200] if sanitized else "document"
+ return sanitize_filename(filename)
def _build_pdf_options(self) -> dict[str, Any]:
pdf_format = self.format if self.format in self.VALID_FORMATS else "A4"
@@ -9120,6 +9099,7 @@ from skyvern.forge.sdk.workflow.models.google_sheets_blocks import ( # noqa: E4
GoogleSheetsReadBlock,
GoogleSheetsWriteBlock,
)
+from skyvern.forge.sdk.workflow.models.pdf_fill_block import PdfFillBlock # noqa: E402
BlockSubclasses = Union[
ConditionalBlock,
@@ -9149,6 +9129,7 @@ BlockSubclasses = Union[
WorkflowTriggerBlock,
GoogleSheetsReadBlock,
GoogleSheetsWriteBlock,
+ PdfFillBlock,
]
BlockTypeVar = Annotated[BlockSubclasses, Field(discriminator="block_type")]
diff --git a/skyvern/forge/sdk/workflow/models/pdf_fill_block.py b/skyvern/forge/sdk/workflow/models/pdf_fill_block.py
new file mode 100644
index 000000000..94d544597
--- /dev/null
+++ b/skyvern/forge/sdk/workflow/models/pdf_fill_block.py
@@ -0,0 +1,928 @@
+from __future__ import annotations
+
+import asyncio
+import csv
+import io
+import json
+import os
+import shutil
+import tempfile
+import time
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any, Literal, cast
+
+import aiofiles
+import structlog
+from pypdf import PdfReader, PdfWriter
+from pypdf.generic import DecodedStreamObject, DictionaryObject, NameObject
+
+from skyvern.config import settings
+from skyvern.constants import GET_DOWNLOADED_FILES_TIMEOUT, SAVE_DOWNLOADED_FILES_TIMEOUT
+from skyvern.exceptions import PDFParsingError
+from skyvern.forge import app
+from skyvern.forge.prompts import prompt_engine
+from skyvern.forge.sdk.api.files import download_file, get_path_for_workflow_download_directory
+from skyvern.forge.sdk.api.llm.api_handler import LLMAPIHandler
+from skyvern.forge.sdk.api.llm.api_handler_factory import LLMAPIHandlerFactory
+from skyvern.forge.sdk.artifact.models import ArtifactType
+from skyvern.forge.sdk.core import skyvern_context
+from skyvern.forge.sdk.db.exceptions import NotFoundError
+from skyvern.forge.sdk.experimentation.llm_prompt_config import get_llm_handler_for_prompt_type
+from skyvern.forge.sdk.schemas.files import FileInfo
+from skyvern.forge.sdk.utils.pdf_parser import render_pdf_pages_as_images, validate_pdf_file
+from skyvern.forge.sdk.workflow.context_manager import WorkflowRunContext
+from skyvern.forge.sdk.workflow.loop_download_filter import filter_downloaded_files_for_current_iteration
+from skyvern.forge.sdk.workflow.models._jinja import render_templates_in_json_value
+from skyvern.forge.sdk.workflow.models.block import (
+ Block,
+ capture_block_download_baseline,
+ extract_file_url_from_block_output,
+ sanitize_filename,
+)
+from skyvern.forge.sdk.workflow.models.parameter import PARAMETER_TYPE
+from skyvern.schemas.workflows import BlockResult, BlockStatus, BlockType
+
+LOG = structlog.get_logger()
+
+FLAT_PDF_OCR_MISSING_MESSAGE = (
+ "This PDF has no fillable AcroForm fields; filling flat PDFs requires the tesseract OCR binary, "
+ "which is not installed on this host."
+)
+FLAT_FILL_RENDER_RESOLUTION = 150
+FLAT_FILL_FONT_SIZE = 11
+FLAT_FILL_OCR_MIN_CONFIDENCE = 30.0
+FLAT_FILL_FONT_RESOURCE = "/SkyvernHelv"
+# Tesseract merges visually aligned table cells into one line; split anchors on column-sized gaps.
+FLAT_FILL_LINE_SPLIT_GAP_PX = 30
+FLAT_FILL_OCR_TIMEOUT_SECONDS = 60
+# Outer budget across all pages so a flat PDF can't pin a worker for the full per-page timeout x max pages.
+FLAT_FILL_OCR_TOTAL_TIMEOUT_SECONDS = 300
+FLAT_FILL_MAX_PAGES = 25
+
+
+@dataclass(frozen=True)
+class PdfFieldInventory:
+ name: str
+ field_type: str
+ current_value: Any
+ allowed_values: list[str]
+
+
+@dataclass(frozen=True)
+class FlatPdfAnchor:
+ anchor_id: int
+ page_index: int
+ text: str
+ x0: int
+ x1: int
+ top: int
+ bottom: int
+ page_width_px: int
+ page_height_px: int
+
+
+@dataclass(frozen=True)
+class FlatPlacement:
+ anchor: FlatPdfAnchor
+ value: str
+ position: str
+
+
+class PdfFillBlock(Block):
+ block_type: Literal[BlockType.PDF_FILL] = BlockType.PDF_FILL # type: ignore
+
+ file_url: str
+ prompt: str
+ payload: dict[str, Any] | list | str | None = None
+ llm_key: str | None = None
+ parameters: list[PARAMETER_TYPE] = []
+
+ def get_all_parameters(self, workflow_run_id: str) -> list[PARAMETER_TYPE]:
+ parameters = list(self.parameters)
+ workflow_run_context = self.get_workflow_run_context(workflow_run_id)
+ if self.file_url and workflow_run_context.has_parameter(self.file_url):
+ parameter = workflow_run_context.get_parameter(self.file_url)
+ if parameter.key not in {existing.key for existing in parameters}:
+ parameters.append(parameter)
+ return parameters
+
+ def format_potential_template_parameters(self, workflow_run_context: WorkflowRunContext) -> None:
+ template_kwargs = {"force_include_secrets": True}
+
+ def _render_string(value: str) -> str:
+ return self.format_block_parameter_template_from_workflow_run_context(
+ value, workflow_run_context, **template_kwargs
+ )
+
+ if (
+ self.file_url
+ and workflow_run_context.has_parameter(self.file_url)
+ and workflow_run_context.has_value(self.file_url)
+ ):
+ file_url_parameter_value = workflow_run_context.get_value(self.file_url)
+ if file_url_parameter_value:
+ self.file_url = extract_file_url_from_block_output(file_url_parameter_value) or file_url_parameter_value
+
+ self.file_url = _render_string(self.file_url)
+ self.prompt = _render_string(self.prompt)
+ if self.llm_key:
+ self.llm_key = _render_string(self.llm_key)
+ self.payload = cast(
+ dict[str, Any] | list | str | None, render_templates_in_json_value(self.payload, _render_string)
+ )
+
+ extracted_url = extract_file_url_from_block_output(self.file_url)
+ if extracted_url:
+ self.file_url = extracted_url
+
+ self._apply_workflow_system_prompt(workflow_run_context)
+
+ async def _resolve_default_llm_handler(self, workflow_run_id: str, organization_id: str | None) -> LLMAPIHandler:
+ prompt_config_handler = await get_llm_handler_for_prompt_type("text-prompt", workflow_run_id, organization_id)
+ if prompt_config_handler:
+ return prompt_config_handler
+
+ secondary_handler = app.SECONDARY_LLM_API_HANDLER
+ if secondary_handler:
+ return secondary_handler
+
+ LOG.warning(
+ "Secondary LLM handler not configured; falling back to primary handler for PdfFillBlock",
+ workflow_run_id=workflow_run_id,
+ organization_id=organization_id,
+ )
+ return app.LLM_API_HANDLER
+
+ async def _record_failure(
+ self,
+ workflow_run_context: WorkflowRunContext,
+ workflow_run_id: str,
+ workflow_run_block_id: str,
+ organization_id: str | None,
+ failure_reason: str,
+ output_parameter_value: dict[str, Any] | None = None,
+ ) -> BlockResult:
+ await self.record_output_parameter_value(workflow_run_context, workflow_run_id, output_parameter_value)
+ return await self.build_block_result(
+ success=False,
+ failure_reason=failure_reason,
+ output_parameter_value=output_parameter_value,
+ status=BlockStatus.failed,
+ workflow_run_block_id=workflow_run_block_id,
+ organization_id=organization_id,
+ )
+
+ async def _resolve_source_pdf(self, organization_id: str | None) -> tuple[str, bool]:
+ # Bare local paths bypass download_file's gating, so only honor them in local dev;
+ # in deployed environments they could read other runs' files off a shared worker.
+ # Returns (path, is_temp): is_temp marks a download_file temp the caller must clean up;
+ # a user-supplied local path is never deleted.
+ if settings.ENV == "local" and os.path.exists(self.file_url):
+ return self.file_url, False
+ return await download_file(self.file_url, organization_id=organization_id), True
+
+ @staticmethod
+ def _dereference(value: Any) -> Any:
+ if hasattr(value, "get_object"):
+ return value.get_object()
+ return value
+
+ @classmethod
+ def _field_allowed_values(cls, field: Any) -> list[str]:
+ values: list[str] = []
+ states = field.get("/_States_")
+ if isinstance(states, list):
+ values.extend(str(state) for state in states)
+
+ kids = field.get("/Kids") or []
+ for kid_ref in kids:
+ kid = cls._dereference(kid_ref)
+ appearances = cls._dereference(kid.get("/AP", {}))
+ normal_appearances = cls._dereference(appearances.get("/N", {}))
+ if isinstance(normal_appearances, dict):
+ values.extend(str(key) for key in normal_appearances.keys())
+
+ options = field.get("/Opt")
+ if options:
+ for option in options:
+ option_value = cls._dereference(option)
+ if isinstance(option_value, (list, tuple)) and option_value:
+ option_value = cls._dereference(option_value[0])
+ values.append(str(option_value))
+
+ deduped: list[str] = []
+ for value in values:
+ if value not in deduped:
+ deduped.append(value)
+ return deduped
+
+ @staticmethod
+ def _field_type(field: Any) -> str:
+ pdf_field_type = str(field.get("/FT", ""))
+ if pdf_field_type == "/Tx":
+ return "text"
+ if pdf_field_type == "/Ch":
+ return "choice"
+ if pdf_field_type == "/Btn":
+ flags = int(field.get("/Ff", 0) or 0)
+ if flags & (1 << 15):
+ return "radio"
+ return "checkbox"
+ return "text"
+
+ def _extract_field_inventory(self, reader: PdfReader) -> dict[str, PdfFieldInventory]:
+ fields = reader.get_fields() or {}
+ inventory: dict[str, PdfFieldInventory] = {}
+ for name, field in fields.items():
+ inventory[name] = PdfFieldInventory(
+ name=name,
+ field_type=self._field_type(field),
+ current_value=field.get("/V"),
+ allowed_values=self._field_allowed_values(field),
+ )
+ return inventory
+
+ async def _map_fields_with_llm(
+ self,
+ inventory: dict[str, PdfFieldInventory],
+ workflow_run_id: str,
+ workflow_run_block_id: str,
+ organization_id: str | None,
+ ) -> dict[str, Any]:
+ default_llm_handler = await self._resolve_default_llm_handler(workflow_run_id, organization_id)
+ llm_api_handler = LLMAPIHandlerFactory.get_override_llm_api_handler(
+ self.override_llm_key or self.llm_key,
+ default=default_llm_handler,
+ )
+ prompt = prompt_engine.load_prompt(
+ "pdf-fill-field-mapping",
+ field_inventory=[field.__dict__ for field in inventory.values()],
+ user_prompt=self.prompt,
+ payload_json=json.dumps(self.payload, indent=2, default=str),
+ )
+ response = await llm_api_handler(
+ prompt=prompt,
+ prompt_name="pdf-fill-field-mapping",
+ system_prompt=self.workflow_system_prompt,
+ workflow_run_block_id=workflow_run_block_id,
+ organization_id=organization_id,
+ )
+ return self._parse_llm_json_response(response, expected_key="fields")
+
+ @staticmethod
+ def _parse_llm_json_response(response: Any, expected_key: str) -> dict[str, Any]:
+ parsed: Any
+ if isinstance(response, str):
+ parsed = json.loads(response)
+ elif expected_key in response:
+ return cast(dict[str, Any], response)
+ elif "llm_response" in response and isinstance(response["llm_response"], str):
+ parsed = json.loads(response["llm_response"])
+ else:
+ parsed = response
+ if not isinstance(parsed, dict):
+ LOG.warning(
+ "PdfFillBlock LLM response was not a JSON object",
+ expected_key=expected_key,
+ response_type=type(parsed).__name__,
+ )
+ return {}
+ if expected_key not in parsed:
+ LOG.warning(
+ "PdfFillBlock LLM response missing expected key",
+ expected_key=expected_key,
+ response_keys=list(parsed.keys()),
+ )
+ return parsed
+
+ @staticmethod
+ def _checked_state(allowed_values: list[str]) -> str | None:
+ for value in allowed_values:
+ if value != "/Off":
+ return value
+ return None
+
+ @staticmethod
+ def _coerce_allowed_value(value: Any, allowed_values: list[str]) -> str | None:
+ value_str = str(value)
+ if value_str in allowed_values:
+ return value_str
+ prefixed = f"/{value_str}"
+ if prefixed in allowed_values:
+ return prefixed
+ return None
+
+ def _sanitize_mapping(
+ self,
+ raw_response: dict[str, Any],
+ inventory: dict[str, PdfFieldInventory],
+ ) -> tuple[dict[str, str], list[dict[str, Any]]]:
+ raw_fields = raw_response.get("fields")
+ if not isinstance(raw_fields, dict):
+ return {}, [{"field_name": None, "reason": "LLM response did not include a fields object"}]
+
+ sanitized: dict[str, str] = {}
+ skipped: list[dict[str, Any]] = []
+ for field_name, value in raw_fields.items():
+ if field_name not in inventory:
+ skipped.append({"field_name": field_name, "reason": "Field is not present in the PDF", "value": value})
+ continue
+
+ field = inventory[field_name]
+ if field.field_type == "checkbox":
+ checked_state = self._checked_state(field.allowed_values)
+ value_str = str(value).strip().lower()
+ wants_checked = value is True or value_str in {"true", "yes", "y", "1", "checked"}
+ wants_unchecked = value is False or value_str in {"false", "no", "n", "0", "off", "/off", "unchecked"}
+ if wants_checked and not checked_state:
+ skipped.append(
+ {"field_name": field_name, "reason": "Checkbox has no known checked state", "value": value}
+ )
+ continue
+ if wants_checked:
+ sanitized[field_name] = cast(str, checked_state)
+ continue
+ if wants_unchecked:
+ sanitized[field_name] = "/Off"
+ continue
+ allowed = self._coerce_allowed_value(value, field.allowed_values)
+ if allowed:
+ sanitized[field_name] = allowed
+ continue
+ skipped.append({"field_name": field_name, "reason": "Invalid checkbox value", "value": value})
+ continue
+
+ if field.field_type in {"radio", "choice"}:
+ allowed = (
+ self._coerce_allowed_value(value, field.allowed_values) if field.allowed_values else str(value)
+ )
+ if allowed:
+ sanitized[field_name] = allowed
+ else:
+ skipped.append(
+ {
+ "field_name": field_name,
+ "reason": "Value is not one of the allowed options",
+ "value": value,
+ "allowed_values": field.allowed_values,
+ }
+ )
+ continue
+
+ sanitized[field_name] = "" if value is None else str(value)
+
+ return sanitized, skipped
+
+ def _output_path(self, workflow_run_id: str, workflow_run_block_id: str) -> Path:
+ output_dir = get_path_for_workflow_download_directory(workflow_run_id)
+ output_dir.mkdir(parents=True, exist_ok=True)
+ # The run-block id keeps loop iterations from overwriting each other's filled PDF.
+ suffix = f"_{workflow_run_block_id}" if workflow_run_block_id else ""
+ filename = f"{sanitize_filename(self.label, default='pdf_fill')}{suffix}_filled.pdf"
+ return output_dir / filename
+
+ async def _fill_with_skyvern(self, reader: PdfReader, fields: dict[str, str], output_path: Path) -> bytes:
+ writer = PdfWriter()
+ writer.clone_document_from_reader(reader)
+ writer.set_need_appearances_writer(True)
+ # page=None fills all pages (writer.pages is a _VirtualList and fails pypdf's isinstance(page, list) check).
+ # auto_regenerate=None keeps NeedAppearances as set above; a bool would overwrite it.
+ writer.update_page_form_field_values(None, fields, auto_regenerate=None)
+ buffer = io.BytesIO()
+ writer.write(buffer)
+ pdf_bytes = buffer.getvalue()
+ async with aiofiles.open(output_path, "wb") as f:
+ await f.write(pdf_bytes)
+ return pdf_bytes
+
+ @staticmethod
+ def _tesseract_available() -> bool:
+ return shutil.which("tesseract") is not None
+
+ async def _extract_flat_anchors(self, pdf_path: str) -> list[FlatPdfAnchor]:
+ page_images = render_pdf_pages_as_images(
+ pdf_path,
+ file_identifier=self.file_url,
+ max_pages=FLAT_FILL_MAX_PAGES,
+ resolution=FLAT_FILL_RENDER_RESOLUTION,
+ )
+ anchors: list[FlatPdfAnchor] = []
+ deadline = time.monotonic() + FLAT_FILL_OCR_TOTAL_TIMEOUT_SECONDS
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ for page_index, image_bytes in enumerate(page_images):
+ page_budget = min(FLAT_FILL_OCR_TIMEOUT_SECONDS, deadline - time.monotonic())
+ if page_budget <= 0:
+ raise ValueError(
+ f"OCR exceeded the total budget of {FLAT_FILL_OCR_TOTAL_TIMEOUT_SECONDS}s "
+ f"before finishing all pages (stopped at page {page_index})"
+ )
+ image_path = os.path.join(tmp_dir, f"page_{page_index}.png")
+ async with aiofiles.open(image_path, "wb") as f:
+ await f.write(image_bytes)
+ process = await asyncio.create_subprocess_exec(
+ "tesseract",
+ image_path,
+ "stdout",
+ "tsv",
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.DEVNULL,
+ )
+ try:
+ async with asyncio.timeout(page_budget):
+ stdout, _ = await process.communicate()
+ except TimeoutError:
+ process.kill()
+ await process.wait()
+ raise ValueError(f"tesseract OCR timed out on page {page_index}")
+ if process.returncode != 0:
+ raise ValueError(f"tesseract OCR failed on page {page_index} (exit code {process.returncode})")
+ anchors.extend(
+ self._parse_tesseract_tsv(stdout.decode("utf-8", errors="replace"), page_index, len(anchors))
+ )
+ return anchors
+
+ @staticmethod
+ def _tsv_int(row: dict[str, str], key: str) -> int | None:
+ try:
+ return int(row.get(key) or 0)
+ except ValueError:
+ return None
+
+ @classmethod
+ def _parse_tesseract_tsv(cls, tsv_text: str, page_index: int, id_offset: int) -> list[FlatPdfAnchor]:
+ rows = csv.DictReader(io.StringIO(tsv_text), delimiter="\t", quoting=csv.QUOTE_NONE)
+ page_width_px = 0
+ page_height_px = 0
+ lines: dict[tuple[str, str, str], list[dict[str, int | str]]] = {}
+ for row in rows:
+ level = cls._tsv_int(row, "level")
+ if level == 1:
+ page_width_px = cls._tsv_int(row, "width") or 0
+ page_height_px = cls._tsv_int(row, "height") or 0
+ if level != 5:
+ continue
+ text = (row.get("text") or "").strip()
+ if not text:
+ continue
+ try:
+ confidence = float(row.get("conf") or -1)
+ except ValueError:
+ confidence = -1.0
+ if confidence < FLAT_FILL_OCR_MIN_CONFIDENCE:
+ continue
+ left = cls._tsv_int(row, "left")
+ top = cls._tsv_int(row, "top")
+ width = cls._tsv_int(row, "width")
+ height = cls._tsv_int(row, "height")
+ if left is None or top is None or width is None or height is None:
+ continue
+ line_key = (row.get("block_num") or "0", row.get("par_num") or "0", row.get("line_num") or "0")
+ lines.setdefault(line_key, []).append(
+ {"text": text, "left": left, "top": top, "right": left + width, "bottom": top + height}
+ )
+
+ anchors: list[FlatPdfAnchor] = []
+ for words in lines.values():
+ ordered = sorted(words, key=lambda word: cast(int, word["left"]))
+ segments: list[list[dict[str, int | str]]] = [[ordered[0]]]
+ for word in ordered[1:]:
+ previous_right = cast(int, segments[-1][-1]["right"])
+ if cast(int, word["left"]) - previous_right > FLAT_FILL_LINE_SPLIT_GAP_PX:
+ segments.append([word])
+ else:
+ segments[-1].append(word)
+ for segment in segments:
+ anchors.append(
+ FlatPdfAnchor(
+ anchor_id=id_offset + len(anchors),
+ page_index=page_index,
+ text=" ".join(cast(str, word["text"]) for word in segment),
+ x0=min(cast(int, word["left"]) for word in segment),
+ x1=max(cast(int, word["right"]) for word in segment),
+ top=min(cast(int, word["top"]) for word in segment),
+ bottom=max(cast(int, word["bottom"]) for word in segment),
+ page_width_px=page_width_px,
+ page_height_px=page_height_px,
+ )
+ )
+ return anchors
+
+ async def _map_flat_placements_with_llm(
+ self,
+ anchors: list[FlatPdfAnchor],
+ workflow_run_id: str,
+ workflow_run_block_id: str,
+ organization_id: str | None,
+ ) -> dict[str, Any]:
+ default_llm_handler = await self._resolve_default_llm_handler(workflow_run_id, organization_id)
+ llm_api_handler = LLMAPIHandlerFactory.get_override_llm_api_handler(
+ self.override_llm_key or self.llm_key,
+ default=default_llm_handler,
+ )
+ prompt = prompt_engine.load_prompt(
+ "pdf-fill-flat-placement",
+ anchors=[anchor.__dict__ for anchor in anchors],
+ user_prompt=self.prompt,
+ payload_json=json.dumps(self.payload, indent=2, default=str),
+ )
+ response = await llm_api_handler(
+ prompt=prompt,
+ prompt_name="pdf-fill-flat-placement",
+ system_prompt=self.workflow_system_prompt,
+ workflow_run_block_id=workflow_run_block_id,
+ organization_id=organization_id,
+ )
+ return self._parse_llm_json_response(response, expected_key="placements")
+
+ @staticmethod
+ def _sanitize_placements(
+ raw_response: dict[str, Any],
+ anchors: list[FlatPdfAnchor],
+ ) -> tuple[list[FlatPlacement], list[dict[str, Any]]]:
+ raw_placements = raw_response.get("placements")
+ if not isinstance(raw_placements, list):
+ return [], [{"anchor_id": None, "reason": "LLM response did not include a placements list"}]
+
+ anchors_by_id = {anchor.anchor_id: anchor for anchor in anchors}
+ placements: list[FlatPlacement] = []
+ used_anchor_ids: set[int] = set()
+ skipped: list[dict[str, Any]] = []
+ for item in raw_placements:
+ if not isinstance(item, dict):
+ skipped.append({"anchor_id": None, "reason": "Placement is not an object", "value": item})
+ continue
+ try:
+ anchor_id = int(item.get("anchor_id")) # type: ignore[arg-type]
+ except (TypeError, ValueError):
+ skipped.append({"anchor_id": item.get("anchor_id"), "reason": "Invalid anchor_id"})
+ continue
+ anchor = anchors_by_id.get(anchor_id)
+ if anchor is None:
+ skipped.append({"anchor_id": anchor_id, "reason": "anchor_id was not detected on the PDF"})
+ continue
+ if anchor_id in used_anchor_ids:
+ skipped.append({"anchor_id": anchor_id, "reason": "Duplicate placement for the same anchor"})
+ continue
+ value = item.get("value")
+ if not isinstance(value, str) or not value.strip():
+ skipped.append({"anchor_id": anchor_id, "reason": "Missing or empty value", "value": value})
+ continue
+ try:
+ value.encode("latin-1")
+ except UnicodeEncodeError:
+ skipped.append(
+ {
+ "anchor_id": anchor_id,
+ "reason": "Value contains characters the flat-PDF overlay font cannot render",
+ "value": value,
+ }
+ )
+ continue
+ position = item.get("position")
+ if position not in ("right", "below"):
+ position = "right"
+ used_anchor_ids.add(anchor_id)
+ placements.append(FlatPlacement(anchor=anchor, value=value.strip(), position=position))
+ return placements, skipped
+
+ @staticmethod
+ def _escape_pdf_text(value: str) -> str:
+ single_line = " ".join(value.split())
+ return single_line.replace("\\", r"\\").replace("(", r"\(").replace(")", r"\)")
+
+ async def _fill_flat_overlay(self, reader: PdfReader, placements: list[FlatPlacement], output_path: Path) -> bytes:
+ writer = PdfWriter()
+ writer.clone_document_from_reader(reader)
+
+ placements_by_page: dict[int, list[FlatPlacement]] = {}
+ for placement in placements:
+ placements_by_page.setdefault(placement.anchor.page_index, []).append(placement)
+
+ for page_index, page_placements in placements_by_page.items():
+ if page_index >= len(writer.pages):
+ continue
+ page = writer.pages[page_index]
+ # pdfplumber renders the page's CROPBOX region, so OCR pixel coordinates map to the
+ # cropbox (which can differ from the media box and have a nonzero origin).
+ crop_box = page.cropbox
+ page_width = float(crop_box.width)
+ page_height = float(crop_box.height)
+ origin_x = float(crop_box.left)
+ origin_y = float(crop_box.bottom)
+ text_ops: list[str] = []
+ for placement in page_placements:
+ anchor = placement.anchor
+ if not anchor.page_width_px or not anchor.page_height_px:
+ continue
+ scale_x = page_width / anchor.page_width_px
+ scale_y = page_height / anchor.page_height_px
+ if placement.position == "below":
+ text_x = origin_x + anchor.x0 * scale_x + 8
+ text_y = origin_y + page_height - anchor.bottom * scale_y - FLAT_FILL_FONT_SIZE - 3
+ else:
+ text_x = origin_x + anchor.x1 * scale_x + 6
+ text_y = origin_y + page_height - anchor.bottom * scale_y - 1
+ text_ops.append(
+ f"BT {FLAT_FILL_FONT_RESOURCE} {FLAT_FILL_FONT_SIZE} Tf 0 0 0 rg "
+ f"{text_x:.1f} {text_y:.1f} Td ({self._escape_pdf_text(placement.value)}) Tj ET"
+ )
+ if not text_ops:
+ continue
+
+ overlay_writer = PdfWriter()
+ overlay_page = overlay_writer.add_blank_page(width=page_width, height=page_height)
+ # Mirror the target's cropbox bounds on the overlay page: merge_page composites and clips
+ # relative to the incoming page's boxes, so matching boxes keep absolute coordinates intact.
+ overlay_page.mediabox.lower_left = (origin_x, origin_y)
+ overlay_page.mediabox.upper_right = (origin_x + page_width, origin_y + page_height)
+ content_stream = DecodedStreamObject()
+ # _sanitize_placements already rejects non-latin-1 values, so strict makes any future gap
+ # fail loudly instead of silently writing a corrupted overlay.
+ content_stream.set_data("\n".join(text_ops).encode("latin-1"))
+ overlay_page[NameObject("/Contents")] = overlay_writer._add_object(content_stream)
+ font = DictionaryObject(
+ {
+ NameObject("/Type"): NameObject("/Font"),
+ NameObject("/Subtype"): NameObject("/Type1"),
+ NameObject("/BaseFont"): NameObject("/Helvetica"),
+ }
+ )
+ overlay_page[NameObject("/Resources")] = DictionaryObject(
+ {
+ NameObject("/Font"): DictionaryObject(
+ {NameObject(FLAT_FILL_FONT_RESOURCE): overlay_writer._add_object(font)}
+ )
+ }
+ )
+ # merge_page wraps the original content in a balanced graphics state; appending raw streams
+ # inherits any unbalanced CTM left by the source document and teleports the overlay.
+ page.merge_page(overlay_page)
+
+ buffer = io.BytesIO()
+ writer.write(buffer)
+ pdf_bytes = buffer.getvalue()
+ async with aiofiles.open(output_path, "wb") as f:
+ await f.write(pdf_bytes)
+ return pdf_bytes
+
+ async def _upload_pdf_artifact(
+ self,
+ *,
+ pdf_bytes: bytes,
+ workflow_run_id: str,
+ workflow_run_block_id: str,
+ workflow_run_context: WorkflowRunContext,
+ organization_id: str | None,
+ ) -> tuple[str | None, str | None]:
+ artifact_org_id = organization_id or workflow_run_context.organization_id
+ if not artifact_org_id:
+ return None, None
+ try:
+ workflow_run_block = await app.DATABASE.observer.get_workflow_run_block(
+ workflow_run_block_id,
+ organization_id=artifact_org_id,
+ )
+ except NotFoundError:
+ return None, None
+
+ artifact_id, artifact_uri = await app.ARTIFACT_MANAGER.create_workflow_run_block_artifact_with_uri(
+ workflow_run_block=workflow_run_block,
+ artifact_type=ArtifactType.PDF,
+ data=pdf_bytes,
+ )
+ try:
+ await app.ARTIFACT_MANAGER.wait_for_upload_aiotasks([workflow_run_block.workflow_run_block_id])
+ except Exception:
+ LOG.warning("PdfFillBlock failed to upload PDF artifact", workflow_run_id=workflow_run_id, exc_info=True)
+ return None, None
+
+ artifact_url = None
+ try:
+ artifact = await app.DATABASE.artifacts.get_artifact_by_id(artifact_id, organization_id=artifact_org_id)
+ if artifact:
+ artifact_url = await app.ARTIFACT_MANAGER.get_share_link(artifact)
+ except Exception:
+ LOG.warning("PdfFillBlock failed to generate artifact download URL", artifact_id=artifact_id, exc_info=True)
+ return artifact_uri, artifact_url
+
+ async def _register_pdf_as_downloaded_file(
+ self,
+ *,
+ organization_id: str | None,
+ workflow_run_id: str,
+ workflow_run_block_id: str,
+ ) -> list[FileInfo]:
+ if not organization_id:
+ return []
+ try:
+ async with asyncio.timeout(SAVE_DOWNLOADED_FILES_TIMEOUT):
+ await app.STORAGE.save_downloaded_files(organization_id=organization_id, run_id=workflow_run_id)
+ except Exception:
+ LOG.warning(
+ "PdfFillBlock failed to register filled PDF as downloaded file",
+ workflow_run_id=workflow_run_id,
+ workflow_run_block_id=workflow_run_block_id,
+ exc_info=True,
+ )
+ return []
+ try:
+ async with asyncio.timeout(GET_DOWNLOADED_FILES_TIMEOUT):
+ return await app.STORAGE.get_downloaded_files(organization_id=organization_id, run_id=workflow_run_id)
+ except Exception:
+ return []
+
+ async def execute(
+ self,
+ workflow_run_id: str,
+ workflow_run_block_id: str,
+ organization_id: str | None = None,
+ browser_session_id: str | None = None,
+ **kwargs: Any,
+ ) -> BlockResult:
+ workflow_run_context = self.get_workflow_run_context(workflow_run_id)
+ block_context = skyvern_context.current()
+ if block_context and organization_id:
+ await capture_block_download_baseline(block_context, organization_id, workflow_run_id, self.label)
+
+ try:
+ self.format_potential_template_parameters(workflow_run_context)
+ except Exception as e:
+ return await self._record_failure(
+ workflow_run_context,
+ workflow_run_id,
+ workflow_run_block_id,
+ organization_id,
+ f"Failed to format jinja template: {str(e)}",
+ )
+
+ try:
+ source_pdf_path, source_is_temp = await self._resolve_source_pdf(organization_id)
+ except Exception as e:
+ return await self._record_failure(
+ workflow_run_context,
+ workflow_run_id,
+ workflow_run_block_id,
+ organization_id,
+ f"Failed to load PDF: {str(e)}",
+ )
+
+ try:
+ try:
+ validate_pdf_file(source_pdf_path, file_identifier=self.file_url)
+ reader = PdfReader(source_pdf_path)
+ inventory = self._extract_field_inventory(reader)
+ except PDFParsingError as e:
+ return await self._record_failure(
+ workflow_run_context,
+ workflow_run_id,
+ workflow_run_block_id,
+ organization_id,
+ f"Invalid PDF file: {str(e)}",
+ )
+ except Exception as e:
+ return await self._record_failure(
+ workflow_run_context,
+ workflow_run_id,
+ workflow_run_block_id,
+ organization_id,
+ f"Failed to load PDF: {str(e)}",
+ )
+
+ if not inventory and not self._tesseract_available():
+ return await self._record_failure(
+ workflow_run_context,
+ workflow_run_id,
+ workflow_run_block_id,
+ organization_id,
+ FLAT_PDF_OCR_MISSING_MESSAGE,
+ )
+
+ fill_mode = "acroform" if inventory else "flat_overlay"
+ try:
+ output_path = self._output_path(workflow_run_id, workflow_run_block_id)
+ if inventory:
+ raw_mapping = await self._map_fields_with_llm(
+ inventory,
+ workflow_run_id,
+ workflow_run_block_id,
+ organization_id,
+ )
+ fields, skipped_fields = self._sanitize_mapping(raw_mapping, inventory)
+ if not fields:
+ skipped_summary = "; ".join(
+ f"{item.get('field_name')}: {item.get('reason')}" for item in skipped_fields[:5]
+ )
+ return await self._record_failure(
+ workflow_run_context,
+ workflow_run_id,
+ workflow_run_block_id,
+ organization_id,
+ "PDF Fill could not map any payload values to the PDF's form fields. "
+ f"Skipped: {skipped_summary or 'no fields proposed'}",
+ output_parameter_value={"fields": {}, "skipped_fields": skipped_fields},
+ )
+ pdf_bytes = await self._fill_with_skyvern(reader, fields, output_path)
+ else:
+ if len(reader.pages) > FLAT_FILL_MAX_PAGES:
+ return await self._record_failure(
+ workflow_run_context,
+ workflow_run_id,
+ workflow_run_block_id,
+ organization_id,
+ f"Flat PDF filling supports up to {FLAT_FILL_MAX_PAGES} pages; "
+ f"this PDF has {len(reader.pages)}.",
+ )
+ anchors = await self._extract_flat_anchors(source_pdf_path)
+ if not anchors:
+ return await self._record_failure(
+ workflow_run_context,
+ workflow_run_id,
+ workflow_run_block_id,
+ organization_id,
+ "OCR did not detect any text on the PDF pages, so there are no labels to fill against.",
+ )
+ raw_placements = await self._map_flat_placements_with_llm(
+ anchors,
+ workflow_run_id,
+ workflow_run_block_id,
+ organization_id,
+ )
+ placements, skipped_fields = self._sanitize_placements(raw_placements, anchors)
+ if not placements:
+ skipped_summary = "; ".join(
+ f"{item.get('anchor_id')}: {item.get('reason')}" for item in skipped_fields[:5]
+ )
+ return await self._record_failure(
+ workflow_run_context,
+ workflow_run_id,
+ workflow_run_block_id,
+ organization_id,
+ "PDF Fill could not place any payload values on the flat PDF. "
+ f"Skipped: {skipped_summary or 'no placements proposed'}",
+ output_parameter_value={"fields": {}, "skipped_fields": skipped_fields},
+ )
+ fields = {placement.anchor.text: placement.value for placement in placements}
+ pdf_bytes = await self._fill_flat_overlay(reader, placements, output_path)
+ except Exception as e:
+ return await self._record_failure(
+ workflow_run_context,
+ workflow_run_id,
+ workflow_run_block_id,
+ organization_id,
+ f"PDF Fill failed: {str(e)}",
+ )
+
+ artifact_uri, artifact_url = await self._upload_pdf_artifact(
+ pdf_bytes=pdf_bytes,
+ workflow_run_id=workflow_run_id,
+ workflow_run_block_id=workflow_run_block_id,
+ workflow_run_context=workflow_run_context,
+ organization_id=organization_id,
+ )
+ artifact_org_id = organization_id or workflow_run_context.organization_id
+ downloaded_files = await self._register_pdf_as_downloaded_file(
+ organization_id=artifact_org_id,
+ workflow_run_id=workflow_run_id,
+ workflow_run_block_id=workflow_run_block_id,
+ )
+ current_context = skyvern_context.current()
+ downloaded_files = filter_downloaded_files_for_current_iteration(
+ downloaded_files,
+ current_context.loop_internal_state if current_context else None,
+ )
+ # The run-level download list can hold other blocks' files; narrow to this block's filled PDF so a
+ # downstream block consuming `{{ this_output }}` resolves to the right file (extract_file_url reads [0]).
+ own_downloaded_files = [
+ fi for fi in downloaded_files if fi.filename == output_path.name
+ ] or downloaded_files
+
+ output = {
+ "fill_mode": fill_mode,
+ "fields": fields,
+ "skipped_fields": skipped_fields,
+ "file_path": str(output_path),
+ "file_name": output_path.name,
+ "file_size": output_path.stat().st_size,
+ "artifact_uri": artifact_uri,
+ "artifact_url": artifact_url,
+ "downloaded_files": [fi.model_dump() for fi in own_downloaded_files],
+ "downloaded_file_urls": [fi.url for fi in own_downloaded_files],
+ "downloaded_file_artifact_ids": [fi.artifact_id for fi in own_downloaded_files if fi.artifact_id],
+ }
+ output = workflow_run_context.mask_secrets_in_data(output)
+ await self.record_output_parameter_value(workflow_run_context, workflow_run_id, output)
+ return await self.build_block_result(
+ success=True,
+ failure_reason=None,
+ output_parameter_value=output,
+ status=BlockStatus.completed,
+ workflow_run_block_id=workflow_run_block_id,
+ organization_id=organization_id,
+ )
+ finally:
+ if source_is_temp and os.path.exists(source_pdf_path):
+ try:
+ os.remove(source_pdf_path)
+ except OSError:
+ LOG.warning("PdfFillBlock failed to clean up downloaded source PDF", path=source_pdf_path)
diff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.py
index 24934bb5c..0a90d7ff2 100644
--- a/skyvern/forge/sdk/workflow/service.py
+++ b/skyvern/forge/sdk/workflow/service.py
@@ -85,6 +85,7 @@ from skyvern.forge.sdk.workflow.models.block import (
ForLoopBlock,
LoginBlock,
NavigationBlock,
+ PdfFillBlock,
PDFParserBlock,
TaskV2Block,
TextPromptBlock,
@@ -125,6 +126,7 @@ from skyvern.forge.sdk.workflow.status_mapping import (
TASK_STATUS_MAP,
)
from skyvern.forge.sdk.workflow.workflow_definition_converter import convert_workflow_definition
+from skyvern.schemas.run_enums import RunEngine
from skyvern.schemas.runs import (
ProxyLocationInput,
RunStatus,
@@ -273,14 +275,15 @@ def _collect_enterprise_gated_workflow_features(
for block in blocks_to_check:
# TaskV2Block deliberately stays out of this set: its inherited model field is not consumed at runtime.
- task_block_uses_engine_and_model = (
- isinstance(block, BaseTaskBlock) and block.block_type != BlockType.HUMAN_INTERACTION
- )
+ engine: RunEngine | None = None
+ task_block_uses_engine_and_model = False
+ if isinstance(block, BaseTaskBlock) and block.block_type != BlockType.HUMAN_INTERACTION:
+ task_block_uses_engine_and_model = True
+ engine = block.engine
block_uses_model = task_block_uses_engine_and_model or isinstance(
block,
- (TextPromptBlock, FileParserBlock, PDFParserBlock),
+ (TextPromptBlock, FileParserBlock, PDFParserBlock, PdfFillBlock),
)
- engine = block.engine if task_block_uses_engine_and_model else None
model = block.model if block_uses_model else None
feature_names.update(
collect_enterprise_gated_run_features(
diff --git a/skyvern/forge/sdk/workflow/workflow_definition_converter.py b/skyvern/forge/sdk/workflow/workflow_definition_converter.py
index 3d4a72ca9..a3a8f4168 100644
--- a/skyvern/forge/sdk/workflow/workflow_definition_converter.py
+++ b/skyvern/forge/sdk/workflow/workflow_definition_converter.py
@@ -83,6 +83,7 @@ from skyvern.forge.sdk.workflow.models.parameter import (
WorkflowParameter,
WorkflowParameterType,
)
+from skyvern.forge.sdk.workflow.models.pdf_fill_block import PdfFillBlock
from skyvern.forge.sdk.workflow.models.workflow import (
WorkflowDefinition,
)
@@ -792,6 +793,17 @@ def block_yaml_to_block(
parameters=print_page_block_parameters,
)
+ elif block_yaml.block_type == BlockType.PDF_FILL:
+ pdf_fill_block_parameters = _resolve_block_parameters(block_yaml, parameters)
+ return PdfFillBlock(
+ **base_kwargs,
+ file_url=block_yaml.file_url,
+ prompt=block_yaml.prompt,
+ payload=block_yaml.payload,
+ llm_key=block_yaml.llm_key,
+ parameters=pdf_fill_block_parameters,
+ )
+
elif block_yaml.block_type == BlockType.WORKFLOW_TRIGGER:
workflow_trigger_block_parameters = _resolve_block_parameters(block_yaml, parameters)
return WorkflowTriggerBlock(
diff --git a/skyvern/schemas/workflows.py b/skyvern/schemas/workflows.py
index 7288a43e7..f21da0861 100644
--- a/skyvern/schemas/workflows.py
+++ b/skyvern/schemas/workflows.py
@@ -441,6 +441,7 @@ class BlockType(StrEnum):
WORKFLOW_TRIGGER = "workflow_trigger"
GOOGLE_SHEETS_READ = "google_sheets_read"
GOOGLE_SHEETS_WRITE = "google_sheets_write"
+ PDF_FILL = "pdf_fill"
class AIFallbackMode(StrEnum):
@@ -1112,6 +1113,49 @@ class PrintPageBlockYAML(BlockYAML):
parameter_keys: list[str] | None = None
+class PdfFillBlockYAML(BlockYAML):
+ block_type: Literal[BlockType.PDF_FILL] = BlockType.PDF_FILL # type: ignore
+ file_url: str
+ prompt: str
+ payload: dict[str, Any] | list | str | None = None
+ llm_key: str | None = None
+ parameter_keys: list[str] | None = None
+
+ @model_validator(mode="after")
+ def normalize_llm_selection(self) -> "PdfFillBlockYAML":
+ raw_llm_key = self.llm_key.strip() if self.llm_key else None
+
+ if self.model:
+ self.llm_key = None
+ return self
+
+ if not raw_llm_key:
+ self.llm_key = None
+ return self
+
+ if _has_jinja_syntax(raw_llm_key):
+ self.llm_key = raw_llm_key
+ return self
+
+ model_name = _get_text_prompt_model_name_by_llm_key().get(raw_llm_key)
+ if model_name:
+ self.model = {"model_name": model_name}
+ self.llm_key = None
+ return self
+
+ if raw_llm_key in LLMConfigRegistry.get_model_names():
+ self.llm_key = raw_llm_key
+ return self
+
+ LOG.warning(
+ "Unrecognized pdf fill llm_key; defaulting to Skyvern Optimized/default model path",
+ label=self.label,
+ llm_key=raw_llm_key,
+ )
+ self.llm_key = None
+ return self
+
+
class WorkflowTriggerBlockYAML(BlockYAML):
block_type: Literal[BlockType.WORKFLOW_TRIGGER] = BlockType.WORKFLOW_TRIGGER # type: ignore
@@ -1191,6 +1235,7 @@ BLOCK_YAML_SUBCLASSES = (
| HttpRequestBlockYAML
| ConditionalBlockYAML
| PrintPageBlockYAML
+ | PdfFillBlockYAML
| WorkflowTriggerBlockYAML
| GoogleSheetsReadBlockYAML
| GoogleSheetsWriteBlockYAML
diff --git a/tests/smoke_tests/test_pdf_fill_block.py b/tests/smoke_tests/test_pdf_fill_block.py
new file mode 100644
index 000000000..5468770cf
--- /dev/null
+++ b/tests/smoke_tests/test_pdf_fill_block.py
@@ -0,0 +1,168 @@
+"""End-to-end smoke tests for the pdf_fill block: YAML definition -> converter -> execute.
+
+External boundaries (LLM, tesseract subprocess) are faked; PDF parsing, templating,
+sanitization, filling, and overlay rendering all run for real.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any
+from unittest.mock import AsyncMock, MagicMock
+
+import pdfplumber
+import pytest
+from pypdf import PdfReader
+
+from skyvern.forge.sdk.workflow.models.block import PdfFillBlock
+from skyvern.forge.sdk.workflow.workflow_definition_converter import convert_workflow_definition
+from skyvern.schemas.workflows import BlockStatus, PdfFillBlockYAML, WorkflowDefinitionYAML
+from tests.unit.fake_workflow_run_context import FakeWorkflowRunContext
+from tests.unit.test_pdf_fill_block import _write_fillable_pdf, _write_flat_pdf
+
+
+class SmokePdfFillContext(FakeWorkflowRunContext):
+ organization_id = None
+
+ def has_parameter(self, key: str) -> bool:
+ return key in self.values
+
+ def get_value(self, key: str) -> Any:
+ return self.values[key]
+
+ def resolve_effective_workflow_system_prompt(self, *_args: Any, **_kwargs: Any) -> None:
+ return None
+
+ def record_block_workflow_system_prompt(self, *_args: Any, **_kwargs: Any) -> None:
+ return None
+
+ async def register_output_parameter_value_post_execution(self, parameter: Any, value: Any) -> None:
+ self.set_value(parameter.key, value)
+
+
+def _build_pdf_fill_block(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, **yaml_overrides: Any) -> PdfFillBlock:
+ yaml_kwargs: dict[str, Any] = {
+ "block_type": "pdf_fill",
+ "label": "fill_form",
+ "file_url": "{{ source_pdf }}",
+ "prompt": "Fill the form from the payload.",
+ "payload": {"name": "Jane A Doe"},
+ }
+ yaml_kwargs.update(yaml_overrides)
+ definition = convert_workflow_definition(
+ WorkflowDefinitionYAML(parameters=[], blocks=[PdfFillBlockYAML(**yaml_kwargs)]),
+ workflow_id="wf_pdf_fill_smoke",
+ )
+ block = definition.blocks[0]
+ assert isinstance(block, PdfFillBlock)
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.workflow.models.pdf_fill_block.get_path_for_workflow_download_directory",
+ lambda workflow_run_id: tmp_path / "downloads" / workflow_run_id,
+ )
+ return block
+
+
+def _install_context(monkeypatch: pytest.MonkeyPatch, values: dict[str, Any]) -> SmokePdfFillContext:
+ context = SmokePdfFillContext(values=values)
+ monkeypatch.setattr(PdfFillBlock, "get_workflow_run_context", staticmethod(lambda _wr_id: context))
+ mock_app = MagicMock()
+ mock_app.DATABASE.workflow_runs.create_or_update_workflow_run_output_parameter = AsyncMock()
+ mock_app.DATABASE.observer.update_workflow_run_block = AsyncMock()
+ monkeypatch.setattr("skyvern.forge.sdk.workflow.models.pdf_fill_block.app", mock_app)
+ monkeypatch.setattr("skyvern.forge.sdk.workflow.models.block.app", mock_app)
+ return context
+
+
+async def test_acroform_fill_end_to_end_through_converter(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ source_pdf = tmp_path / "form.pdf"
+ _write_fillable_pdf(source_pdf)
+
+ async def _llm_response(**_: Any) -> dict[str, Any]:
+ return {"fields": {"name": "Jane A Doe", "subscribe": True}, "thought": "mapped"}
+
+ block = _build_pdf_fill_block(monkeypatch, tmp_path)
+ context = _install_context(monkeypatch, values={"source_pdf": str(source_pdf)})
+ monkeypatch.setattr(PdfFillBlock, "_resolve_default_llm_handler", AsyncMock(return_value=_llm_response))
+
+ result = await block.execute(workflow_run_id="wr_smoke_acroform", workflow_run_block_id="", organization_id=None)
+
+ assert result.success is True
+ assert result.status == BlockStatus.completed
+ output = result.output_parameter_value
+ assert output["fill_mode"] == "acroform"
+ filled_fields = PdfReader(output["file_path"]).get_fields()
+ assert filled_fields["name"]["/V"] == "Jane A Doe"
+ assert filled_fields["subscribe"]["/V"] == "/Yes"
+ assert context.values["fill_form_output"]["fill_mode"] == "acroform"
+
+
+async def test_flat_fill_end_to_end_with_fake_tesseract(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ source_pdf = tmp_path / "flat.pdf"
+ _write_flat_pdf(source_pdf)
+
+ # The 300x200pt flat fixture renders to 625x417px at 150dpi; the TSV mirrors a real tesseract run.
+ tsv = (
+ "level\tpage_num\tblock_num\tpar_num\tline_num\tword_num\tleft\ttop\twidth\theight\tconf\ttext\n"
+ "1\t1\t0\t0\t0\t0\t0\t0\t625\t417\t-1\t\n"
+ "5\t1\t1\t1\t1\t1\t40\t60\t60\t14\t92.0\tName:\n"
+ )
+
+ class FakeProcess:
+ returncode = 0
+
+ async def communicate(self) -> tuple[bytes, bytes]:
+ return tsv.encode(), b""
+
+ def kill(self) -> None:
+ pass
+
+ async def wait(self) -> int:
+ return 0
+
+ async def fake_subprocess(*_args: Any, **_kwargs: Any) -> FakeProcess:
+ return FakeProcess()
+
+ async def _llm_response(**_: Any) -> dict[str, Any]:
+ return {"placements": [{"anchor_id": 0, "value": "Jane A Doe", "position": "right"}], "thought": "placed"}
+
+ block = _build_pdf_fill_block(monkeypatch, tmp_path)
+ context = _install_context(monkeypatch, values={"source_pdf": str(source_pdf)})
+ monkeypatch.setattr(PdfFillBlock, "_tesseract_available", staticmethod(lambda: True))
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.workflow.models.pdf_fill_block.asyncio.create_subprocess_exec", fake_subprocess
+ )
+ monkeypatch.setattr(PdfFillBlock, "_resolve_default_llm_handler", AsyncMock(return_value=_llm_response))
+
+ result = await block.execute(workflow_run_id="wr_smoke_flat", workflow_run_block_id="", organization_id=None)
+
+ assert result.success is True
+ output = result.output_parameter_value
+ assert output["fill_mode"] == "flat_overlay"
+ assert output["fields"] == {"Name:": "Jane A Doe"}
+ with pdfplumber.open(output["file_path"]) as pdf:
+ words = {w["text"] for w in pdf.pages[0].extract_words()}
+ assert "Jane" in words
+ assert context.values["fill_form_output"]["fill_mode"] == "flat_overlay"
+
+
+async def test_file_url_unwraps_upstream_block_output(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ source_pdf = tmp_path / "form.pdf"
+ _write_fillable_pdf(source_pdf)
+
+ async def _llm_response(**_: Any) -> dict[str, Any]:
+ return {"fields": {"name": "Jane A Doe"}, "thought": "mapped"}
+
+ block = _build_pdf_fill_block(monkeypatch, tmp_path, file_url="downloader_output")
+ _install_context(
+ monkeypatch,
+ values={"downloader_output": {"downloaded_files": [{"url": str(source_pdf)}]}},
+ )
+ monkeypatch.setattr(PdfFillBlock, "_resolve_default_llm_handler", AsyncMock(return_value=_llm_response))
+
+ result = await block.execute(workflow_run_id="wr_smoke_chained", workflow_run_block_id="", organization_id=None)
+
+ assert result.success is True
+ assert PdfReader(result.output_parameter_value["file_path"]).get_fields()["name"]["/V"] == "Jane A Doe"
diff --git a/tests/unit/test_mcp_block_tools.py b/tests/unit/test_mcp_block_tools.py
index 647e5bb77..ceae16231 100644
--- a/tests/unit/test_mcp_block_tools.py
+++ b/tests/unit/test_mcp_block_tools.py
@@ -58,5 +58,22 @@ async def test_block_schema_no_type_lists_all() -> None:
block_types = result["data"]["block_types"]
assert "navigation" in block_types
assert "extraction" in block_types
+ assert "pdf_fill" in block_types
assert "task" not in block_types
assert result["data"]["count"] > 0
+
+
+async def test_block_validate_pdf_fill() -> None:
+ block = {
+ "block_type": "pdf_fill",
+ "label": "fill_pdf",
+ "file_url": "{{ source_pdf }}",
+ "prompt": "Fill the PDF using the payload.",
+ "payload": {"name": "{{ applicant.name }}"},
+ "parameter_keys": ["source_pdf", "applicant"],
+ }
+ result = await skyvern_block_validate(block_json=json.dumps(block))
+
+ assert result["ok"] is True
+ assert result["data"]["valid"] is True
diff --git a/tests/unit/test_mcp_block_type_parity.py b/tests/unit/test_mcp_block_type_parity.py
index 9ee5c6fee..5c6b5a44d 100644
--- a/tests/unit/test_mcp_block_type_parity.py
+++ b/tests/unit/test_mcp_block_type_parity.py
@@ -94,7 +94,15 @@ class BlockDriftEntry:
# Allowlist: block types present in the backend but not yet regenerated into
# the vendored Fern SDK. Run `fern generate` using the Skyvern Cloud-only
# runbook to resync, then remove the entry here.
-_KNOWN_DRIFT_ALLOWLIST: tuple[BlockDriftEntry, ...] = ()
+_KNOWN_DRIFT_ALLOWLIST: tuple[BlockDriftEntry, ...] = (
+ BlockDriftEntry(
+ block_type="pdf_fill",
+ ticket="SKY-10944",
+ owner="@suchintan",
+ added_at=date(2026, 6, 11),
+ notes="Fern SDK regen happens via CI post-deploy",
+ ),
+)
def _allowlisted_block_types() -> set[str]:
diff --git a/tests/unit/test_mcp_workflow_list_drift.py b/tests/unit/test_mcp_workflow_list_drift.py
index e1d6c7ba3..f38fc2f21 100644
--- a/tests/unit/test_mcp_workflow_list_drift.py
+++ b/tests/unit/test_mcp_workflow_list_drift.py
@@ -38,6 +38,10 @@ def _make_workflow_dict(workflow_id: str, block_type: str, *, label: str = "step
block["range"] = "A1:D100"
block["credential_id"] = "{{ google_credential_id }}"
block["has_header_row"] = True
+ elif block_type == "pdf_fill":
+ block["file_url"] = "{{ source_pdf }}"
+ block["prompt"] = "Fill the PDF using the payload."
+ block["payload"] = {"name": "{{ applicant.name }}"}
elif block_type == "navigation":
block["url"] = "https://example.com"
block["navigation_goal"] = "do the thing"
@@ -91,6 +95,7 @@ async def test_list_succeeds_when_workflow_uses_google_sheets_block(monkeypatch:
payload = [
_make_workflow_dict("wpid_ok", "navigation"),
_make_workflow_dict("wpid_sheets", "google_sheets_read"),
+ _make_workflow_dict("wpid_pdf_fill", "pdf_fill"),
]
request_mock = _patch_skyvern_list_response(monkeypatch, payload=payload)
@@ -98,10 +103,10 @@ async def test_list_succeeds_when_workflow_uses_google_sheets_block(monkeypatch:
assert result["ok"] is True, result
data = result["data"]
- assert data["count"] == 2
+ assert data["count"] == 3
assert data["page"] == 1
ids = {wf["workflow_permanent_id"] for wf in data["workflows"]}
- assert ids == {"wpid_ok", "wpid_sheets"}
+ assert ids == {"wpid_ok", "wpid_sheets", "wpid_pdf_fill"}
request_mock.assert_awaited_once()
call = request_mock.await_args
diff --git a/tests/unit/test_mcp_workflow_tools.py b/tests/unit/test_mcp_workflow_tools.py
index f31e384e2..35b4ba7c6 100644
--- a/tests/unit/test_mcp_workflow_tools.py
+++ b/tests/unit/test_mcp_workflow_tools.py
@@ -79,22 +79,30 @@ def _patch_skyvern_http(
return request_mock
-def _google_sheets_definition(block_type: str) -> dict[str, object]:
+def _known_drift_definition(block_type: str) -> dict[str, object]:
block: dict[str, object] = {
"block_type": block_type,
"label": f"{block_type}_step",
- "spreadsheet_url": "https://docs.google.com/spreadsheets/d/SPREADSHEET_ID/edit",
- "sheet_name": "Sheet1",
- "range": "A1:D100",
- "credential_id": "{{ google_credential_id }}",
}
if block_type == "google_sheets_read":
+ block["spreadsheet_url"] = "https://docs.google.com/spreadsheets/d/SPREADSHEET_ID/edit"
+ block["sheet_name"] = "Sheet1"
+ block["range"] = "A1:D100"
+ block["credential_id"] = "{{ google_credential_id }}"
block["has_header_row"] = True
elif block_type == "google_sheets_write":
+ block["spreadsheet_url"] = "https://docs.google.com/spreadsheets/d/SPREADSHEET_ID/edit"
+ block["sheet_name"] = "Sheet1"
+ block["range"] = "A1:D100"
+ block["credential_id"] = "{{ google_credential_id }}"
block["write_mode"] = "append"
block["values"] = "{{ output_data | tojson }}"
+ elif block_type == "pdf_fill":
+ block["file_url"] = "{{ source_pdf }}"
+ block["prompt"] = "Fill the PDF using the payload."
+ block["payload"] = {"name": "{{ applicant.name }}"}
else:
- raise ValueError(f"Unsupported google sheets block type: {block_type}")
+ raise ValueError(f"Unsupported known drift block type: {block_type}")
return {
"title": f"{block_type} workflow",
@@ -155,13 +163,13 @@ def _heavy_workflow_run_payload(*, include_expanded_outputs: bool = True) -> dic
}
[email protected]("block_type", ["google_sheets_read", "google_sheets_write"])
[email protected]("block_type", ["google_sheets_read", "google_sheets_write", "pdf_fill"])
@pytest.mark.asyncio
-async def test_workflow_create_sends_google_sheets_json_definition_as_raw_dict(
+async def test_workflow_create_sends_known_drift_json_definition_as_raw_dict(
monkeypatch: pytest.MonkeyPatch, block_type: str
) -> None:
request_mock = _patch_skyvern_http(monkeypatch, response_payload=_fake_workflow_dict())
- definition = _google_sheets_definition(block_type)
+ definition = _known_drift_definition(block_type)
result = await workflow_tools.skyvern_workflow_create(definition=json.dumps(definition), format="json")
@@ -171,12 +179,15 @@ async def test_workflow_create_sends_google_sheets_json_definition_as_raw_dict(
assert not hasattr(sent_definition, "model_dump")
sent_block = sent_definition["workflow_definition"]["blocks"][0]
assert sent_block["block_type"] == block_type
- assert sent_block["spreadsheet_url"] == "https://docs.google.com/spreadsheets/d/SPREADSHEET_ID/edit"
+ if block_type.startswith("google_sheets"):
+ assert sent_block["spreadsheet_url"] == "https://docs.google.com/spreadsheets/d/SPREADSHEET_ID/edit"
+ else:
+ assert sent_block["file_url"] == "{{ source_pdf }}"
[email protected]("block_type", ["google_sheets_read", "google_sheets_write"])
[email protected]("block_type", ["google_sheets_read", "google_sheets_write", "pdf_fill"])
@pytest.mark.asyncio
-async def test_workflow_update_sends_google_sheets_json_definition_as_raw_dict(
+async def test_workflow_update_sends_known_drift_json_definition_as_raw_dict(
monkeypatch: pytest.MonkeyPatch, block_type: str
) -> None:
request_mock = _patch_skyvern_http(monkeypatch, response_payload=_fake_workflow_dict())
@@ -193,7 +204,7 @@ async def test_workflow_update_sends_google_sheets_json_definition_as_raw_dict(
}
_patch_get_workflow_by_id(monkeypatch, fake_get_workflow_by_id)
- definition = _google_sheets_definition(block_type)
+ definition = _known_drift_definition(block_type)
result = await workflow_tools.skyvern_workflow_update(
workflow_id="wpid_test",
@@ -207,7 +218,10 @@ async def test_workflow_update_sends_google_sheets_json_definition_as_raw_dict(
assert not hasattr(sent_definition, "model_dump")
sent_block = sent_definition["workflow_definition"]["blocks"][0]
assert sent_block["block_type"] == block_type
- assert sent_block["spreadsheet_url"] == "https://docs.google.com/spreadsheets/d/SPREADSHEET_ID/edit"
+ if block_type.startswith("google_sheets"):
+ assert sent_block["spreadsheet_url"] == "https://docs.google.com/spreadsheets/d/SPREADSHEET_ID/edit"
+ else:
+ assert sent_block["file_url"] == "{{ source_pdf }}"
@pytest.mark.asyncio
diff --git a/tests/unit/test_pdf_fill_block.py b/tests/unit/test_pdf_fill_block.py
new file mode 100644
index 000000000..ef014f48e
--- /dev/null
+++ b/tests/unit/test_pdf_fill_block.py
@@ -0,0 +1,617 @@
+from __future__ import annotations
+
+from datetime import UTC, datetime
+from pathlib import Path
+from typing import Any
+from unittest.mock import AsyncMock
+
+import pytest
+from pypdf import PdfReader, PdfWriter
+from pypdf.generic import (
+ ArrayObject,
+ BooleanObject,
+ DecodedStreamObject,
+ DictionaryObject,
+ FloatObject,
+ NameObject,
+ NumberObject,
+ RectangleObject,
+ TextStringObject,
+)
+
+from skyvern.forge import app
+from skyvern.forge.sdk.workflow.context_manager import WorkflowRunContext
+from skyvern.forge.sdk.workflow.models.block import PdfFillBlock, extract_file_url_from_block_output
+from skyvern.forge.sdk.workflow.models.parameter import OutputParameter
+from skyvern.forge.sdk.workflow.models.pdf_fill_block import FlatPdfAnchor, FlatPlacement, PdfFieldInventory
+from skyvern.forge.sdk.workflow.workflow_definition_converter import block_yaml_to_block
+from skyvern.schemas.workflows import BlockStatus, BlockType, PdfFillBlockYAML
+
+
+def _make_output_parameter(label: str = "fill_pdf") -> OutputParameter:
+ now = datetime.now(UTC)
+ return OutputParameter(
+ output_parameter_id=f"{label}_output_id",
+ workflow_id="workflow-id",
+ key=f"{label}_output",
+ created_at=now,
+ modified_at=now,
+ )
+
+
+def _make_block(**overrides: Any) -> PdfFillBlock:
+ data: dict[str, Any] = {
+ "label": "fill_pdf",
+ "output_parameter": _make_output_parameter(),
+ "file_url": "source.pdf",
+ "prompt": "Fill the PDF.",
+ }
+ data.update(overrides)
+ return PdfFillBlock(**data)
+
+
+def _install_context(monkeypatch: pytest.MonkeyPatch, run_id: str = "run_pdf_fill") -> WorkflowRunContext:
+ context = WorkflowRunContext(
+ workflow_title="PDF Fill Test",
+ workflow_id="workflow-id",
+ workflow_permanent_id="wpid-pdf-fill",
+ workflow_run_id=run_id,
+ aws_client=AsyncMock(),
+ )
+ monkeypatch.setattr(PdfFillBlock, "get_workflow_run_context", staticmethod(lambda _wr_id: context))
+ monkeypatch.setattr(
+ app.DATABASE.workflow_runs,
+ "create_or_update_workflow_run_output_parameter",
+ AsyncMock(),
+ )
+ return context
+
+
+def _add_empty_appearance(writer: PdfWriter, states: list[str]) -> DictionaryObject:
+ normal_appearances = DictionaryObject()
+ for state in states:
+ stream = DecodedStreamObject()
+ stream.set_data(b"")
+ normal_appearances[NameObject(state)] = writer._add_object(stream)
+ return DictionaryObject({NameObject("/N"): normal_appearances})
+
+
+def _write_fillable_pdf(path: Path) -> None:
+ writer = PdfWriter()
+ page = writer.add_blank_page(width=300, height=200)
+ fields = ArrayObject()
+ annotations = ArrayObject()
+
+ text_field = DictionaryObject(
+ {
+ NameObject("/FT"): NameObject("/Tx"),
+ NameObject("/T"): TextStringObject("name"),
+ NameObject("/V"): TextStringObject(""),
+ }
+ )
+ text_field_ref = writer._add_object(text_field)
+ text_widget = DictionaryObject(
+ {
+ NameObject("/Subtype"): NameObject("/Widget"),
+ NameObject("/Type"): NameObject("/Annot"),
+ NameObject("/Rect"): ArrayObject([FloatObject(50), FloatObject(150), FloatObject(250), FloatObject(170)]),
+ NameObject("/F"): NumberObject(4),
+ NameObject("/P"): page.indirect_reference,
+ NameObject("/Parent"): text_field_ref,
+ }
+ )
+ text_widget_ref = writer._add_object(text_widget)
+ text_field[NameObject("/Kids")] = ArrayObject([text_widget_ref])
+ fields.append(text_field_ref)
+ annotations.append(text_widget_ref)
+
+ checkbox_field = DictionaryObject(
+ {
+ NameObject("/FT"): NameObject("/Btn"),
+ NameObject("/T"): TextStringObject("subscribe"),
+ NameObject("/V"): NameObject("/Off"),
+ }
+ )
+ checkbox_field_ref = writer._add_object(checkbox_field)
+ checkbox_widget = DictionaryObject(
+ {
+ NameObject("/Subtype"): NameObject("/Widget"),
+ NameObject("/Type"): NameObject("/Annot"),
+ NameObject("/Rect"): ArrayObject([FloatObject(50), FloatObject(100), FloatObject(65), FloatObject(115)]),
+ NameObject("/F"): NumberObject(4),
+ NameObject("/P"): page.indirect_reference,
+ NameObject("/Parent"): checkbox_field_ref,
+ NameObject("/AP"): _add_empty_appearance(writer, ["/Yes", "/Off"]),
+ NameObject("/AS"): NameObject("/Off"),
+ }
+ )
+ checkbox_widget_ref = writer._add_object(checkbox_widget)
+ checkbox_field[NameObject("/Kids")] = ArrayObject([checkbox_widget_ref])
+ fields.append(checkbox_field_ref)
+ annotations.append(checkbox_widget_ref)
+
+ page[NameObject("/Annots")] = annotations
+ writer._root_object.update(
+ {
+ NameObject("/AcroForm"): DictionaryObject(
+ {NameObject("/Fields"): fields, NameObject("/NeedAppearances"): BooleanObject(True)}
+ )
+ }
+ )
+ with path.open("wb") as f:
+ writer.write(f)
+
+
+def _write_flat_pdf(path: Path) -> None:
+ writer = PdfWriter()
+ writer.add_blank_page(width=300, height=200)
+ with path.open("wb") as f:
+ writer.write(f)
+
+
+async def _fake_llm_response(**_: Any) -> dict[str, Any]:
+ return {"fields": {"name": "Jane", "subscribe": True}, "thought": "matched fields"}
+
+
+async def test_skyvern_engine_fills_pdf_with_llm_mapping(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ run_id = "run_skyvern_pdf_fill"
+ _install_context(monkeypatch, run_id)
+ source_pdf = tmp_path / "source.pdf"
+ _write_fillable_pdf(source_pdf)
+ assert PdfReader(str(source_pdf)).get_fields()
+
+ monkeypatch.setattr(PdfFillBlock, "_resolve_default_llm_handler", AsyncMock(return_value=_fake_llm_response))
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.workflow.models.pdf_fill_block.get_path_for_workflow_download_directory",
+ lambda workflow_run_id: tmp_path / "downloads" / workflow_run_id,
+ )
+
+ block = _make_block(file_url=str(source_pdf), payload={"name": "Jane", "subscribe": True})
+ result = await block.execute(workflow_run_id=run_id, workflow_run_block_id="", organization_id=None)
+
+ assert result.success is True
+ assert result.status == BlockStatus.completed
+ assert result.output_parameter_value is not None
+ output = result.output_parameter_value
+ output_path = Path(output["file_path"])
+ assert output_path.exists()
+ assert output["file_name"] == "fill_pdf_filled.pdf"
+ assert output["file_size"] == output_path.stat().st_size
+ assert output["fields"] == {"name": "Jane", "subscribe": "/Yes"}
+ assert output["skipped_fields"] == []
+
+ output_reader = PdfReader(str(output_path))
+ fields = output_reader.get_fields()
+ assert fields["name"]["/V"] == "Jane"
+ assert fields["subscribe"]["/V"] == "/Yes"
+ assert bool(output_reader.trailer["/Root"]["/AcroForm"]["/NeedAppearances"]) is True
+
+
+def test_mapping_sanitization_skips_unknown_fields_and_coerces_checkbox(tmp_path: Path) -> None:
+ source_pdf = tmp_path / "source.pdf"
+ _write_fillable_pdf(source_pdf)
+ block = _make_block(file_url=str(source_pdf))
+ inventory = block._extract_field_inventory(PdfReader(str(source_pdf)))
+
+ fields, skipped = block._sanitize_mapping(
+ {"fields": {"name": "Jane", "subscribe": True, "unknown": "ignored"}},
+ inventory,
+ )
+
+ assert fields == {"name": "Jane", "subscribe": "/Yes"}
+ assert skipped == [{"field_name": "unknown", "reason": "Field is not present in the PDF", "value": "ignored"}]
+
+
+def test_extract_file_url_from_block_output_precedence() -> None:
+ # downloaded_files[0] wins when present; url before file_path within the entry.
+ assert (
+ extract_file_url_from_block_output(
+ {"downloaded_files": [{"url": "s3://a", "file_path": "/tmp/a"}], "artifact_url": "s3://art"}
+ )
+ == "s3://a"
+ )
+ assert extract_file_url_from_block_output({"downloaded_files": [{"file_path": "/tmp/a"}]}) == "/tmp/a"
+ # FileDownload/HttpRequest-style outputs without downloaded_files fall back to the widened keys, in order.
+ assert extract_file_url_from_block_output({"artifact_url": "s3://art", "file_path": "/tmp/a"}) == "s3://art"
+ assert extract_file_url_from_block_output({"file_url": "s3://f", "file_path": "/tmp/a"}) == "s3://f"
+ assert extract_file_url_from_block_output({"file_path": "/tmp/a"}) == "/tmp/a"
+ # empty downloaded_files is not treated as a match; falls through to the keyed fallback.
+ assert extract_file_url_from_block_output({"downloaded_files": [], "file_path": "/tmp/a"}) == "/tmp/a"
+ assert extract_file_url_from_block_output({"nothing": "useful"}) is None
+ # string inputs are parsed (JSON, then python-literal) before unwrapping.
+ assert extract_file_url_from_block_output('{"downloaded_files": [{"url": "s3://a"}]}') == "s3://a"
+ assert extract_file_url_from_block_output("not a url") is None
+
+
+def test_parse_llm_json_response_non_dict_returns_empty() -> None:
+ # A JSON array/primitive string must not blow up callers that do .get(expected_key).
+ assert PdfFillBlock._parse_llm_json_response("[]", expected_key="fields") == {}
+ assert PdfFillBlock._parse_llm_json_response("null", expected_key="fields") == {}
+ assert PdfFillBlock._parse_llm_json_response('{"fields": {"a": "b"}}', expected_key="fields") == {
+ "fields": {"a": "b"}
+ }
+
+
+async def test_downloaded_source_pdf_is_cleaned_up(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ run_id = "run_cleanup"
+ _install_context(monkeypatch, run_id)
+ downloaded = tmp_path / "downloaded_source.pdf"
+ _write_fillable_pdf(downloaded)
+
+ async def _fake_download(url: str, **_: Any) -> str:
+ return str(downloaded)
+
+ monkeypatch.setattr("skyvern.forge.sdk.workflow.models.pdf_fill_block.download_file", _fake_download)
+ monkeypatch.setattr("skyvern.forge.sdk.workflow.models.pdf_fill_block.settings.ENV", "production")
+ monkeypatch.setattr(PdfFillBlock, "_resolve_default_llm_handler", AsyncMock(return_value=_fake_llm_response))
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.workflow.models.pdf_fill_block.get_path_for_workflow_download_directory",
+ lambda workflow_run_id: tmp_path / "downloads" / workflow_run_id,
+ )
+
+ block = _make_block(file_url="https://example.com/source.pdf", payload={"name": "Jane"})
+ result = await block.execute(workflow_run_id=run_id, workflow_run_block_id="", organization_id=None)
+
+ assert result.success is True
+ assert not downloaded.exists(), "the downloaded source temp should be removed after execute"
+
+
+def test_checkbox_without_known_state_is_skipped_not_silently_unchecked() -> None:
+ block = _make_block()
+ inventory = {
+ "agree": PdfFieldInventory(name="agree", field_type="checkbox", current_value=None, allowed_values=[]),
+ }
+ fields, skipped = block._sanitize_mapping({"fields": {"agree": True}}, inventory)
+
+ assert fields == {}
+ assert skipped == [{"field_name": "agree", "reason": "Checkbox has no known checked state", "value": True}]
+
+
+async def test_empty_field_mapping_fails(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ run_id = "run_empty_mapping"
+ _install_context(monkeypatch, run_id)
+ source_pdf = tmp_path / "source.pdf"
+ _write_fillable_pdf(source_pdf)
+
+ async def _unmappable_llm_response(**_: Any) -> dict[str, Any]:
+ return {"fields": {"not_a_real_field": "value"}, "thought": "no match"}
+
+ monkeypatch.setattr(PdfFillBlock, "_resolve_default_llm_handler", AsyncMock(return_value=_unmappable_llm_response))
+
+ block = _make_block(file_url=str(source_pdf))
+ result = await block.execute(workflow_run_id=run_id, workflow_run_block_id="", organization_id=None)
+
+ assert result.success is False
+ assert result.status == BlockStatus.failed
+ assert "could not map any payload values" in (result.failure_reason or "")
+ assert result.output_parameter_value["skipped_fields"][0]["field_name"] == "not_a_real_field"
+
+
+async def test_local_path_rejected_outside_local_env(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ run_id = "run_non_local_path"
+ _install_context(monkeypatch, run_id)
+ source_pdf = tmp_path / "source.pdf"
+ _write_fillable_pdf(source_pdf)
+ monkeypatch.setattr("skyvern.forge.sdk.workflow.models.pdf_fill_block.settings.ENV", "production")
+
+ block = _make_block(file_url=str(source_pdf))
+ result = await block.execute(workflow_run_id=run_id, workflow_run_block_id="", organization_id=None)
+
+ assert result.success is False
+ assert result.status == BlockStatus.failed
+
+
+async def test_flat_pdf_without_tesseract_fails(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ run_id = "run_flat_pdf_no_ocr"
+ _install_context(monkeypatch, run_id)
+ flat_pdf = tmp_path / "flat.pdf"
+ _write_flat_pdf(flat_pdf)
+ monkeypatch.setattr(PdfFillBlock, "_tesseract_available", staticmethod(lambda: False))
+
+ block = _make_block(file_url=str(flat_pdf))
+ result = await block.execute(workflow_run_id=run_id, workflow_run_block_id="", organization_id=None)
+
+ assert result.success is False
+ assert result.status == BlockStatus.failed
+ assert "tesseract" in (result.failure_reason or "")
+
+
+async def test_flat_pdf_overlay_fills_with_ocr_anchors(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ run_id = "run_flat_pdf_overlay"
+ _install_context(monkeypatch, run_id)
+ flat_pdf = tmp_path / "flat.pdf"
+ _write_flat_pdf(flat_pdf)
+
+ anchor = FlatPdfAnchor(
+ anchor_id=0,
+ page_index=0,
+ text="Enrollee name:",
+ x0=20,
+ x1=120,
+ top=30,
+ bottom=44,
+ page_width_px=600,
+ page_height_px=400,
+ )
+
+ async def _placement_llm_response(**_: Any) -> dict[str, Any]:
+ return {"placements": [{"anchor_id": 0, "value": "Luis Ortiz", "position": "right"}], "thought": "ok"}
+
+ monkeypatch.setattr(PdfFillBlock, "_tesseract_available", staticmethod(lambda: True))
+ monkeypatch.setattr(PdfFillBlock, "_extract_flat_anchors", AsyncMock(return_value=[anchor]))
+ monkeypatch.setattr(PdfFillBlock, "_resolve_default_llm_handler", AsyncMock(return_value=_placement_llm_response))
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.workflow.models.pdf_fill_block.get_path_for_workflow_download_directory",
+ lambda workflow_run_id: tmp_path / "downloads" / workflow_run_id,
+ )
+
+ block = _make_block(file_url=str(flat_pdf), payload={"personalInfo": {"firstName": "Luis", "lastName": "Ortiz"}})
+ result = await block.execute(workflow_run_id=run_id, workflow_run_block_id="", organization_id=None)
+
+ assert result.success is True
+ output = result.output_parameter_value
+ assert output["fill_mode"] == "flat_overlay"
+ assert output["fields"] == {"Enrollee name:": "Luis Ortiz"}
+ assert output["skipped_fields"] == []
+
+ import pdfplumber
+
+ with pdfplumber.open(output["file_path"]) as pdf:
+ words = pdf.pages[0].extract_words()
+ texts = {w["text"] for w in words}
+ assert "Luis" in texts and "Ortiz" in texts
+ luis = next(w for w in words if w["text"] == "Luis")
+ # page 300x200pt, anchor px scaled by 0.5: expected x ~= 120*0.5+6 = 66, baseline y=177 -> top ~15
+ assert 60 <= luis["x0"] <= 75
+ assert 5 <= luis["top"] <= 25
+
+
+async def test_flat_pdf_over_page_limit_fails(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ run_id = "run_flat_pdf_too_many_pages"
+ _install_context(monkeypatch, run_id)
+ big_pdf = tmp_path / "big.pdf"
+ writer = PdfWriter()
+ for _ in range(26):
+ writer.add_blank_page(width=300, height=200)
+ with big_pdf.open("wb") as f:
+ writer.write(f)
+ monkeypatch.setattr(PdfFillBlock, "_tesseract_available", staticmethod(lambda: True))
+
+ block = _make_block(file_url=str(big_pdf))
+ result = await block.execute(workflow_run_id=run_id, workflow_run_block_id="", organization_id=None)
+
+ assert result.success is False
+ assert "supports up to 25 pages" in (result.failure_reason or "")
+
+
+async def test_flat_overlay_respects_shifted_mediabox(tmp_path: Path) -> None:
+ flat_pdf = tmp_path / "shifted.pdf"
+ writer = PdfWriter()
+ page = writer.add_blank_page(width=300, height=200)
+ page.mediabox.lower_left = (50, 40)
+ page.mediabox.upper_right = (350, 240)
+ with flat_pdf.open("wb") as f:
+ writer.write(f)
+
+ anchor = FlatPdfAnchor(
+ anchor_id=0,
+ page_index=0,
+ text="Name:",
+ x0=20,
+ x1=120,
+ top=30,
+ bottom=44,
+ page_width_px=600,
+ page_height_px=400,
+ )
+ block = _make_block(file_url=str(flat_pdf))
+ output_path = tmp_path / "shifted_filled.pdf"
+ await block._fill_flat_overlay(
+ PdfReader(str(flat_pdf)),
+ [FlatPlacement(anchor=anchor, value="Jane", position="right")],
+ output_path,
+ )
+
+ # pdfplumber's coordinate conventions are unreliable for shifted boxes; assert on rendered pixels.
+ import io as _io
+
+ from PIL import Image
+
+ from skyvern.forge.sdk.utils.pdf_parser import render_pdf_pages_as_images
+
+ image = Image.open(_io.BytesIO(render_pdf_pages_as_images(str(output_path), resolution=150)[0])).convert("L")
+ width, height = image.size
+ pixels = image.load()
+ dark = [(x, y) for y in range(height) for x in range(width) if pixels[x, y] < 128]
+ assert dark, "overlay text did not render inside the page box"
+ min_x = min(x for x, _ in dark)
+ min_y = min(y for _, y in dark)
+ # expected: text starts ~66pt of the 300pt-wide box -> ~0.22 * width; top ~15pt of 200pt -> ~0.075 * height
+ assert 0.18 * width <= min_x <= 0.27 * width
+ assert 0.04 * height <= min_y <= 0.13 * height
+
+
+async def test_flat_overlay_respects_cropbox_distinct_from_mediabox(tmp_path: Path) -> None:
+ flat_pdf = tmp_path / "cropped.pdf"
+ writer = PdfWriter()
+ page = writer.add_blank_page(width=400, height=300)
+ page.cropbox = RectangleObject((50, 40, 350, 240))
+ with flat_pdf.open("wb") as f:
+ writer.write(f)
+
+ anchor = FlatPdfAnchor(
+ anchor_id=0,
+ page_index=0,
+ text="Name:",
+ x0=20,
+ x1=120,
+ top=30,
+ bottom=44,
+ page_width_px=600,
+ page_height_px=400,
+ )
+ block = _make_block(file_url=str(flat_pdf))
+ output_path = tmp_path / "cropped_filled.pdf"
+ await block._fill_flat_overlay(
+ PdfReader(str(flat_pdf)),
+ [FlatPlacement(anchor=anchor, value="Jane", position="right")],
+ output_path,
+ )
+
+ import io as _io
+
+ from PIL import Image
+
+ from skyvern.forge.sdk.utils.pdf_parser import render_pdf_pages_as_images
+
+ image = Image.open(_io.BytesIO(render_pdf_pages_as_images(str(output_path), resolution=150)[0])).convert("L")
+ width, height = image.size
+ pixels = image.load()
+ dark = [(x, y) for y in range(height) for x in range(width) if pixels[x, y] < 128]
+ assert dark, "overlay text did not render inside the cropbox"
+ min_x = min(x for x, _ in dark)
+ min_y = min(y for _, y in dark)
+ # the rendered image covers the 300x200 cropbox; correct mapping puts text at ~66pt/15pt of it
+ assert 0.18 * width <= min_x <= 0.27 * width
+ assert 0.04 * height <= min_y <= 0.13 * height
+
+
+def test_sanitize_placements_filters_invalid_entries() -> None:
+ anchor = FlatPdfAnchor(
+ anchor_id=3,
+ page_index=0,
+ text="Name:",
+ x0=0,
+ x1=50,
+ top=0,
+ bottom=10,
+ page_width_px=600,
+ page_height_px=400,
+ )
+ block = _make_block()
+ placements, skipped = block._sanitize_placements(
+ {
+ "placements": [
+ {"anchor_id": 3, "value": "Jane", "position": "sideways"},
+ {"anchor_id": 99, "value": "ignored"},
+ {"anchor_id": "not-an-int", "value": "ignored"},
+ {"anchor_id": 3, "value": "duplicate anchor"},
+ "not-a-dict",
+ ]
+ },
+ [anchor],
+ )
+
+ assert len(placements) == 1
+ assert placements[0].value == "Jane"
+ assert placements[0].position == "right"
+ assert len(skipped) == 4
+ assert any(item.get("reason") == "Duplicate placement for the same anchor" for item in skipped)
+
+
+def test_sanitize_placements_rejects_non_latin1_values() -> None:
+ anchor = FlatPdfAnchor(
+ anchor_id=1,
+ page_index=0,
+ text="Name:",
+ x0=0,
+ x1=50,
+ top=0,
+ bottom=10,
+ page_width_px=600,
+ page_height_px=400,
+ )
+ block = _make_block()
+ placements, skipped = block._sanitize_placements(
+ {"placements": [{"anchor_id": 1, "value": "名前テスト"}]},
+ [anchor],
+ )
+
+ assert placements == []
+ assert "cannot render" in skipped[0]["reason"]
+
+
+def test_parse_tesseract_tsv_skips_malformed_numeric_rows() -> None:
+ tsv = (
+ "level\tpage_num\tblock_num\tpar_num\tline_num\tword_num\tleft\ttop\twidth\theight\tconf\ttext\n"
+ "1\t1\t0\t0\t0\t0\t0\t0\t600\t400\t-1\t\n"
+ "5\t1\t1\t1\t1\t1\tgarbage\t30\t60\t14\t90.5\tBroken\n"
+ "5\t1\t1\t1\t2\t1\t20\t60\t40\t14\t91.0\tCity:\n"
+ )
+ anchors = PdfFillBlock._parse_tesseract_tsv(tsv, page_index=0, id_offset=0)
+
+ assert [a.text for a in anchors] == ["City:"]
+
+
+def test_escape_pdf_text() -> None:
+ assert PdfFillBlock._escape_pdf_text("A (NM) \\ B\nC") == r"A \(NM\) \\ B C"
+
+
+def test_parse_tesseract_tsv_groups_lines() -> None:
+ tsv = (
+ "level\tpage_num\tblock_num\tpar_num\tline_num\tword_num\tleft\ttop\twidth\theight\tconf\ttext\n"
+ "1\t1\t0\t0\t0\t0\t0\t0\t600\t400\t-1\t\n"
+ "5\t1\t1\t1\t1\t1\t20\t30\t60\t14\t90.5\tEnrollee\n"
+ "5\t1\t1\t1\t1\t2\t85\t31\t35\t13\t88.0\tname:\n"
+ "5\t1\t1\t1\t1\t3\t300\t30\t40\t14\t89.0\tDate:\n"
+ "5\t1\t1\t1\t2\t1\t20\t60\t40\t14\t91.0\tCity:\n"
+ "5\t1\t1\t1\t2\t2\t70\t60\t30\t14\t10.0\tnoise\n"
+ )
+ anchors = PdfFillBlock._parse_tesseract_tsv(tsv, page_index=1, id_offset=5)
+
+ # the table-cell gap between "name:" (ends at 120) and "Date:" (starts at 300) splits the OCR line
+ assert [a.text for a in anchors] == ["Enrollee name:", "Date:", "City:"]
+ first = anchors[0]
+ assert (first.anchor_id, first.page_index) == (5, 1)
+ assert (first.x0, first.x1, first.top, first.bottom) == (20, 120, 30, 44)
+ assert (first.page_width_px, first.page_height_px) == (600, 400)
+ assert anchors[1].x0 == 300
+
+
+async def test_loop_iterations_get_unique_filenames(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ run_id = "run_unique_filename"
+ _install_context(monkeypatch, run_id)
+ source_pdf = tmp_path / "source.pdf"
+ _write_fillable_pdf(source_pdf)
+ monkeypatch.setattr(PdfFillBlock, "_resolve_default_llm_handler", AsyncMock(return_value=_fake_llm_response))
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.workflow.models.pdf_fill_block.get_path_for_workflow_download_directory",
+ lambda workflow_run_id: tmp_path / "downloads" / workflow_run_id,
+ )
+ block = _make_block(file_url=str(source_pdf), payload={"name": "Jane"})
+
+ first = await block.execute(workflow_run_id=run_id, workflow_run_block_id="wrb_iter_0", organization_id=None)
+ second = await block.execute(workflow_run_id=run_id, workflow_run_block_id="wrb_iter_1", organization_id=None)
+
+ assert first.output_parameter_value["file_name"] == "fill_pdf_wrb_iter_0_filled.pdf"
+ assert second.output_parameter_value["file_name"] == "fill_pdf_wrb_iter_1_filled.pdf"
+ assert first.output_parameter_value["file_path"] != second.output_parameter_value["file_path"]
+
+
+def test_pdf_fill_yaml_to_block_conversion() -> None:
+ yaml_block = PdfFillBlockYAML(
+ block_type=BlockType.PDF_FILL,
+ label="fill_pdf",
+ file_url="{{ source_pdf }}",
+ prompt="Fill using payload",
+ payload={"name": "{{ applicant.name }}"},
+ llm_key="{{ llm_key }}",
+ parameter_keys=[],
+ )
+ block = block_yaml_to_block(yaml_block, {"fill_pdf_output": _make_output_parameter()})
+
+ assert isinstance(block, PdfFillBlock)
+ assert block.file_url == "{{ source_pdf }}"
+ assert block.prompt == "Fill using payload"
+ assert block.payload == {"name": "{{ applicant.name }}"}
+ assert block.llm_key == "{{ llm_key }}"