Tag Archives: JavaScript

Agentic Design Patterns – Tool Use Pattern using N8N

Antonio Gulli’s Agentic Design Patterns: A Hands-On Guide to Building Intelligent Systems presents 21 patterns for building AI agents, including prompt chaining, routing, planning, and multi-agent collaboration. The book combines explanations with runnable examples using LangChain, LangGraph, CrewAI, and Google ADK, showing how to assemble individual capabilities into more complex AI workflows. The book uses Python as the implementation language. In this series, I implement the book’s examples using Java and n8n.

Info: This article is part of a series on agentic design patterns. For more workflow examples, see the Pipeline Pattern using Java and n8n, Routing Pattern using Java, and Routing Pattern using n8n.

In this example, an n8n workflow receives a request for a product inventory and order summary report. An OpenAI model calls two SQLite query tools and a third tool that invokes a report-generation sub-workflow. The database queries retrieve the inventory and calculate order totals, the model assembles the results into HTML, and the sub-workflow converts that HTML into PDF and RTF files. All three of these are tools registered for use by the OpenAI model.

The Tool Use pattern gives a language model access to capabilities provided by external software. A language model does not inherently have access to a company’s database or filesystem. The application provides that access through tools, describing their purpose and accepted inputs. The model can then call a tool and supply its arguments. The application executes the operation and returns the result for the model to use.

Info: OpenAI’s function-calling documentation describes using tools (functions) to provide functionality and data and LLM can use to follow instructions and respond to prompts.

Consider a system where users submit different requests about a company’s products and orders. One user might ask for available inventory, another for order totals, and another for a report saved in both formats. Tool calling allows the model to select the available operations appropriate to each request. In n8n, an entire sub-workflow can be exposed as a single tool, allowing the model to request a task that requires several predefined processing steps. n8n’s tool documentation explains these capabilities.

This example provides a small set of tools with deliberately limited responsibilities. The SQLite tools execute fixed queries rather than accepting SQL generated by the model. The report tool accepts HTML and creates both PDF and RTF files. Different prompts could require different combinations of these tools, but this demonstration uses a single predefined prompt.

Info: The source code and supporting resources are available in the main GitHub repository. The n8n workflow JSON files are in the n8n workflows directory.

The following request requires all three tools.

Create a report with all products and order totals grouped by product. 
Include each product’s name, available quantity, and unit price. 
For orders, include the order count, total quantity ordered, and total amount for each product.
Sort both sections by product name and show monetary amounts to two decimal
places. Save the report as PDF and RTF.

The prompt requests a report containing product inventory and order totals grouped by product, with both sections sorted by product name and monetary amounts formatted to two decimal places. The report must be saved as PDF and RTF.

Fulfilling this request requires three tools. The first retrieves product names, available quantities, and unit prices while the second calculates order counts, quantities ordered, and total amounts by product. The third request requires invoking a sub-workflow that converts the model’s HTML report into PDF and RTF files.

Info: This specific report could also be produced by a predefined workflow without AI tool calling. Here, the request is supplied through a Set Prompt node to keep the demonstration simple. The example illustrates how a model can select and call tools—a capability that becomes more useful when users submit varied requests requiring different combinations of operations.

The main workflow

The main execution path contains a manual trigger, Set Prompt, and Message a model nodes.

Three nodes connect to the model through its Tools connector: a product query, an order summary query, and Create and Save PDF and RTF.

When clicking Execute workflow

The manual trigger starts the example when Execute workflow is clicked in the n8n editor.

Set Prompt

Set Prompt is an Edit Fields (Set) node configured for JSON output. It creates a single prompt field containing the report request.

The request asks for all products, including name, available quantity, and unit price, followed by order totals grouped by product. The order section must include the order count, total quantity ordered, and total amount. Both sections should be sorted by product name, monetary amounts should have two decimal places, and the report should be saved as both PDF and RTF.

Message a model

Message a model is an OpenAI node using the Text resource and Message a Model operation through the Responses API. This example uses n8n 2.48.6, where the operation is labeled Message a Model; current n8n documentation calls the Responses API operation Generate a Model Response. This is an OpenAI node with connected tools, rather than an AI Agent node. The selected model in this example is CHAT-LATEST. Its user message reads the request from the previous node with {{ $json.prompt }}.

This node coordinates the task through the connected tools. Rather than receiving database rows in the initial prompt, the model can request the product and order data, use the returned results to compose a report, and call the file-generation tool. n8n executes the tool operations and returns their results to the model.

n8n sends the request and available tool definitions to the model. When the model requests a tool call, n8n executes the operation and returns its output to the model. The model can then request another tool or produce its final response.

Info: The language model does not directly open the SQLite database or write the files. It uses these tools to retrieve the necessary data and write the files.

Execute a SQL query in SQLite: product inventory

The first SQLite tool retrieves every product’s name, quantity, and price. Its manually supplied tool description tells the model what information the operation provides.

Get all products from the database, including
each product's name, quantity, and price.

A tool’s description helps the LLM determine when to call it by explaining what it does and what information or results it provides. The model uses that description alongside the user’s request to select an appropriate tool and, where required, supply the inputs needed to call it.

The query is fixed in the tool’s node.

SELECT name, quantity, price
FROM Products
ORDER BY name;

Execute a SQL query in SQLite1: order totals

The second SQLite tool returns order summaries grouped by product. Its description identifies the product ID, name, order count, total quantity, and total amount, and explicitly states that only products with orders are included.

Get order summaries grouped by product, including each product's ID, name, 
order count, total quantity, and total amount.
Products are sorted by name.
Only products with orders are included.

The query is fixed in the tool’s node.

SELECT p.id AS product_id,
       p.name AS product_name,
       COUNT(*) AS order_count,
       SUM(o.quantity) AS total_quantity,
       SUM(o.quantity * o.unit_price) AS total_amount
FROM Orders o
JOIN Products p ON p.id = o.product_id
GROUP BY p.id, p.name
ORDER BY p.name;

Create and Save PDF and RTF: a workflow exposed as a tool

The third tool, named Create and Save PDF and RTF, is a Call n8n Workflow Tool node. It calls the separate Create and Save PDF and RTF Report workflow. Its description asks for a complete HTML report with headings and simple tables, explains that it creates both formats, and states that the response contains the two saved file paths. It also tells the model that the RTF output supports basic formatting rather than arbitrary CSS.

The tool maps the sub-workflow’s html input using $fromAI:

{{ $fromAI('html', 'Complete product inventory and grouped order totals report as HTML with inline CSS', 'string') }}

The model supplies this parameter when it calls the tool. It contains the report assembled from the database results. The selected workflow comes from n8n’s database, and its final node supplies the tool response. A multi-node workflow is therefore presented to the model as one operation with a defined input and result.

The report-generation sub-workflow

The sub-workflow has six nodes in sequence: Report HTML Input, HTML to PDF, Read/Write Files from Disk, HTML to RTF, Save RTF, and Saved Report Files. Once called, it follows this defined path to convert and save the supplied content.

The Call n8n Workflow Tool node exposes this sub-workflow to the model as a single tool.

Report HTML Input

Report HTML Input is an Execute Sub-workflow Trigger node. It defines one input field named html with type String. This is the boundary between the calling tool and the conversion workflow. The parent supplies the completed report, and the remaining nodes process it.

HTML to PDF

HTML to PDF is a community conversion node configured with HTML String as the source type. It reads {{ $json.html }}, uses Plug & Play (Embedded Binary) mode, and creates output.pdf in the binary field named data. The page options specify A4 portrait.

The node produces PDF binary data. A separate file-writing node is responsible for persisting those bytes to disk.

Read/Write Files from Disk

This node uses Write File to Disk. It reads the data binary field from the PDF converter and writes it to /files/output/output.pdf. This path belongs to the environment running n8n. In a container deployment, access from the host depends on the configured volume mapping.

HTML to RTF

HTML to RTF is a Code node running JavaScript in Run Once for All Items mode. It reads the original HTML from Report HTML Input and converts supported elements into RTF control sequences. It handles headings, paragraphs, lists, emphasis, and simple tables, then prepares output.rtf as binary data in the data field.

Info: For simplicity, a JavaScript Code node implements the HTML-to-RTF conversion.

The converter is intended for basic report content. CSS, images, and merged table cells are not reproduced. Although this node follows the PDF writer, it converts the original HTML rather than converting the PDF. The two formats share the report content but use separate conversion steps.

Save RTF

Save RTF is another Read/Write Files from Disk node configured for Write File to Disk. It takes the RTF bytes from the data field and writes /files/output/output.rtf.

Saved Report Files

The final Edit Fields node returns a small JSON response containing a success flag and both file paths:

{
  "success": true,
  "pdf": "/files/output/output.pdf",
  "rtf": "/files/output/output.rtf"
}

This response goes back to the calling tool and gives the model the locations to report to the user as paths rather than downloadable file attachments. The success: true flag is a configured value returned after the preceding nodes complete; it does not independently validate the documents’ contents or layout.

Setup and execution

This example uses a self-hosted n8n instance running in Docker. Install the community packages n8n-nodes-sqlite3 and n8n-nodes-html2pdf-converter through Settings > Community Nodes. The first supplies the SQLite query tools; the second supplies the HTML to PDF node.

Import pdf-rtf-report-workflow.json and tools-example-workflow.json from the repository’s n8n workflows directory. In the main workflow, open Create and Save PDF and RTF and select the imported Create and Save PDF and RTF Report sub-workflow in the Workflow field. Confirm that its html input is mapped using the existing $fromAI() expression. Select the imported workflow explicitly rather than relying on the exported workflow ID matching the ID in your instance.

Select your OpenAI credential in Message a model and a model available to your account that supports tool calling. Configure a SQLite credential and select it in both query tools. The database must contain the tables and columns used by the queries: Products with id, name, quantity, and price, and Orders with product_id, quantity, and unit_price. Supply the database separately; importing the workflow JSON does not create or populate it. For Docker, make the database available inside the container and use that container path in the SQLite credential.

Provide a writable /files/output directory. The project’s Compose configuration mounts the host directory n8n/storage/files at /files/output and permits file-node access under /files. Confirm that the mount exists and that the n8n process can write to it. The generated files appear in that host directory as output.pdf and output.rtf. Repeated runs write to the same two paths and replace the previous reports.

Save both workflows, open the main workflow, and click Execute workflow. Execution makes live OpenAI API requests and writes the report files. Inspect the execution details to confirm that the model called the two SQLite tools and then supplied HTML to the report-generation tool. The two database queries need not run in a fixed order, but their results should be available before the model assembles the report. If the tool reports a failure, inspect the corresponding node and sub-workflow execution rather than relying only on the model’s final message.

Open both generated files and check the inventory, order totals, sorting, monetary formatting, and document layout. Confirm that the final tool response contains both saved paths. A completed execution and a success: true response do not independently verify the report’s accuracy or formatting.

What this example demonstrates

The tool use (function calling) pattern lets a model request capabilities beyond generating text. Here, the SQLite tools provide current data through fixed queries, and a sub-workflow provides document conversion and disk access through one callable interface. The model’s role is to interpret the request, call the available operations, and assemble the HTML report from their results.

The example also shows why tool descriptions and input contracts matter. Each database tool explains which facts it returns. The report tool specifies the HTML it needs, the files it creates, and the limitations of its RTF conversion. Those details help the model choose and use the operations appropriately.

The tool use pattern allows AI agents to work with external systems. Tools let an agent retrieve current data, run calculations, query databases, and create files. The model interprets the request and selects the tools, while the connected software performs the operations. This gives the agent a way to turn a natural-language request into concrete actions.