Design and Implementation of an n8n-based AI Agent Builder
Why I Built It
Section titled âWhy I Built ItâThe demand for using LLM-based Agents within organizations is growing, but there are the following barriers to actually building and operating Agents:
- Complexity of workflow engines: n8n, LangChain, etc. are powerful but have a high learning curve
- Repetitive boilerplate: Prompt composition, Tool connection, and execution pipelines are duplicated across projects (Tool execution wiring is outside this PoCâs evidenced scope)
- Lack of operational visibility: execution history, error tracking, and cost management are not systematic
The core question of this PoC was simple:
âCan we use n8n as the engine while letting users create and run Agents without knowing n8n?â
Architecture
Section titled âArchitectureâExecution and Security Boundary of a Single-User PoC
Section titled âExecution and Security Boundary of a Single-User PoCâThis is a single-user design PoC that excludes authentication/authorization. Keep the Builder UI/API, n8n editor/API/Webhook, and DB local or on a restricted development network. It is not a deployment baseline for unauthenticated endpoints on the internet or a shared organizational network. The following are requirements before operational use, not controls implemented or verified by this PoC.
- Access control: authenticate/authorize the Builder API separately from restricting n8n editor/API access, and restrict the network so only the Backend can call the Webhook. Configure authentication supported by the deployed version, such as Basic/Header/JWT, on the Webhook as well, and implement the client side to send it. An n8n API key authenticates management API calls; it is not a substitute for Webhook authentication. Compare settings against the 1.94.1 Webhook authentication options.
- Credential ID authorization: select Provider credential IDs from a server-approved mapping. An ID is not the API key value, but neither does it prove permission to use that credential. Do not allow user input to select arbitrary IDs; check credential-use authorization for the Agent, user, and n8n project. Do not pass Provider or n8n API keys to the browser.
- Logs and data: prompts,
dto.input, responses, errors/stacks, and n8n execution data can contain sensitive information. Define masking, read permissions, retention/deletion rules, and use anonymized development-test data. Log calls in this article do not establish that masking was verified.
Overall Structure
Section titled âOverall StructureâIn this architecture, the Tool Selector and Tool storage/API describe the management model. The generated Workflow shown below has neither Tool nodes nor AI Agent Tool connections; selecting a Tool does not mean it can be executed.
Why n8n?
Section titled âWhy n8n?â| Consideration | n8n | LangChain/LangGraph | Custom build |
|---|---|---|---|
| Workflow visualization | â Built-in | â | â |
| AI Agent node | â Built-in | â | Build it yourself |
| Tool integration (Slack, HTTP, etc.) | â 400+ | SDK-based | Build it yourself |
| Self-hosted | â | â | â |
| REST API | â | â | Build it yourself |
| Learning curve (user) | High | Very high | Low |
The key reason for choosing n8n is that you can programmatically control Workflows via the REST API. Without exposing n8n to users, the backend can automatically create/deploy/run Workflows through the n8n API.
Layered Architecture
Section titled âLayered ArchitectureâI applied the Layered Architecture pattern of Domain-Driven Design:
Port Interfaces (Domain Layer)
Section titled âPort Interfaces (Domain Layer)âIn the Domain layer, the Repository Port is defined as a pure TypeScript interface. There is no framework dependency at all:
export interface IAgent { id: string; name: string; description: string; status: AgentStatus; systemPrompt: string; modelConfig: ModelConfig; tools: string[]; createdAt: Date; updatedAt: Date;}
export interface IAgentRepository { findAll(page: number, limit: number, status?: AgentStatus): Promise<{ data: IAgent[]; total: number }>; findById(id: string): Promise<IAgent | null>; create(agent: Partial<IAgent>): Promise<IAgent>; update(id: string, agent: Partial<IAgent>): Promise<IAgent | null>; updateTools(id: string, toolIds: string[]): Promise<IAgent | null>; delete(id: string): Promise<boolean>;}
export const AGENT_REPOSITORY = Symbol('AGENT_REPOSITORY');Service (Domain Layer)
Section titled âService (Domain Layer)âThe Service accesses data only through the Port. The NestJS DI container injects the Adapter via @Inject(AGENT_REPOSITORY):
@Injectable()export class AgentService { constructor( @Inject(AGENT_REPOSITORY) private readonly agentRepository: IAgentRepository, ) {}
async findAll(page = 1, limit = 20, status?: AgentStatus) { return this.agentRepository.findAll(page, limit, status); }
async create(dto: CreateAgentDto) { return this.agentRepository.create({ name: dto.name, description: dto.description, systemPrompt: dto.systemPrompt, modelConfig: dto.modelConfig, tools: dto.tools ?? [], status: 'draft', }); }
async deactivate(id: string) { const agent = await this.agentRepository.findById(id); if (!agent) return null; if (agent.status === 'inactive') { throw new BadRequestException('Agent is already inactive'); } return this.agentRepository.update(id, { status: 'inactive' }); }}Entity (Infrastructure Layer)
Section titled âEntity (Infrastructure Layer)âThe TypeORM Entity is a persistence model that maps tables and columns. AgentRepositoryImpl, which implements the IAgentRepository Repository Port, acts as the Adapter and is injected by the Module below. The Entity stores ModelConfig flexibly with a jsonb column:
@Entity('agents')export class AgentEntity { @PrimaryGeneratedColumn('uuid') id!: string;
@Column({ length: 255 }) name!: string;
@Column({ type: 'varchar', length: 20, default: 'draft' }) status!: AgentStatus;
@Column({ type: 'text', default: '' }) systemPrompt!: string;
@Column({ type: 'jsonb', default: {} }) modelConfig!: ModelConfig;
@ManyToMany(() => ToolEntity, { eager: true }) @JoinTable({ name: 'agent_tools', joinColumn: { name: 'agent_id' }, inverseJoinColumn: { name: 'tool_id' }, }) toolEntities!: ToolEntity[];
@Column({ type: 'jsonb', default: [] }) tools!: string[];
@CreateDateColumn() createdAt!: Date;}Module (DI Binding)
Section titled âModule (DI Binding)âThe NestJS Module binds the Port and the Adapter:
@Module({ providers: [ AgentService, { provide: AGENT_REPOSITORY, useClass: AgentRepositoryImpl }, ],})export class AgentModule {}Core Design
Section titled âCore DesignâAgent Abstraction
Section titled âAgent AbstractionâThe target Agent abstraction has three elements, but the execution path shown in the code below covers Prompt and Config:
| Element | Description | Example |
|---|---|---|
| Prompt | System prompt + variable template | "You are a {{role}}" |
| Tool (extension) | Storing/selecting IDs is distinct from wiring n8n Tool nodes | HTTP Request, Slack, Calculator are candidates, not connected examples |
| Config | Model settings (provider, model, temperature) | Gemini 2.5 Flash, temp=0.7 |
The core of this abstraction is that users donât have to care about the n8n Workflow at all.
IAgent.tools, updateTools(), and the AgentEntity relationship model storing and selecting Tools. In the implementation discussed here, buildAgentWorkflow() accepts a tools input but adds neither Tool nodes nor ai_tool connections to the generated Workflow. The Tool API tests cover listing and Agent assignment, not actual Tool invocations in n8n. Thus the Workflow example below covers the Webhook â AI Agent + Chat Model â response structure; Tool execution wiring remains a separate implementation and verification task.
Automatic Workflow Generation
Section titled âAutomatic Workflow GenerationâWhen you deploy an Agent, the buildAgentWorkflow() function converts the Agent settings into n8n Workflow JSON:
The graph below describes a generated path without Tool connections. The diagram and TypeScript excerpts alone do not prove a successful deployment or Tool execution.
The TypeScript excerpt shows how a Chat Model node is created for each LLM Provider. This branch does not create Tool nodes:
function buildChatModelNode(input: AgentWorkflowInput): N8nNode { if (input.provider === 'anthropic') { return { name: 'Chat Model', type: '@n8n/n8n-nodes-langchain.lmChatAnthropic', typeVersion: 1.2, parameters: { model: input.model || 'claude-sonnet-4-20250514', options: { temperature: input.temperature ?? 0.7, maxTokensToSample: input.maxTokens ?? 4096, }, }, credentials: { anthropicApi: { id: input.credentialId || '', name: 'Anthropic API' }, }, }; }
// Default: Gemini return { name: 'Chat Model', type: '@n8n/n8n-nodes-langchain.lmChatGoogleGemini', typeVersion: 1, parameters: { modelName: input.model || 'models/gemini-2.5-flash', options: { temperature: input.temperature ?? 0.7, maxOutputTokens: input.maxTokens ?? 2048, }, }, credentials: { googlePalmApi: { id: input.credentialId || '', name: 'Google AI (Gemini)' }, }, };}The shown N8nIntegrationService excerpt describes a path intended to create and activate a Workflow using this template:
async deployAgent(input: DeployAgentInput): Promise<DeployResult> { const webhookPath = `agent-${input.agentId}`; const workflowDef = buildAgentWorkflow({ agentId: input.agentId, agentName: input.agentName, systemPrompt: input.systemPrompt, model: input.model, provider: input.provider ?? 'gemini', webhookPath, credentialId, });
// Sequential reuse â update if found, otherwise create const existing = await this.findWorkflowByName(workflowDef.name!); let workflow: N8nWorkflow; if (existing) { workflow = await this.client.updateWorkflow(existing.id, workflowDef); } else { workflow = await this.client.createWorkflow(workflowDef); }
if (!workflow.active) { await this.client.activateWorkflow(workflow.id); } // ...}The name lookup followed by update/create describes intended reuse in sequential calls where one Workflow with that name can be found. Lookup and creation are not atomic: concurrent requests can both create, and duplicate names or conflicting configuration updates are not prevented. Each execution deploys rendered into a shared Workflow, so another concurrent request can overwrite its system prompt. Workflow reuse is also separate from execution idempotency that prevents duplicate LLM calls/costs when a Webhook is retried. Persisted workflow IDs and Agent/config revision mappings, deployment serialization or request isolation, execution idempotency keys, and timeout/retry/state recovery remain separate design and verification tasks.
Execution Pipeline
Section titled âExecution PipelineâAgent execution consists of a 6-stage pipeline. The ExecutionService orchestrates the entire flow:
Actual Mapping of Prompt and Webhook Input
Section titled âActual Mapping of Prompt and Webhook InputâThe excerpt shows rendered being computed, but omits the arguments to deployAgent({ ... }) and the definitions of message and startTime. Following the original repository reference in the articleâs history, I read execution.service.ts, n8n-integration.service.ts, and agent-workflow.ts at private-source revision f752fc290906b80f49f4f7cd19f81992a42e0552 and confirmed the mapping below. This is source inspection, not evidence of a successful execution. Since the source is not publicly accessible, only the non-sensitive mapping is summarized for readers.
| Value | Confirmed Data Path | Meaning and Limit |
|---|---|---|
dto.input | Stored as execution input and used as variables for renderTemplate(agent.systemPrompt, variables) | as Record<string, string> is a type assertion, not runtime input validation |
rendered | deployAgent({ systemPrompt: rendered, ... }) â buildAgentWorkflow() â AI Agent parameters.options.systemMessage | AI Agent system prompt; the original also stores it as renderedPrompt |
message | dto.input.message ?? rendered â executeAgent(path, message) â Webhook JSON { message } | Falls back to rendered as user input when no explicit message exists; this does not equate its role with the system prompt |
| Webhook body | AI Agent text: '={{ $json.body.message }}' | Expression for the user Prompt; actual evaluation/model response remains unverified |
startTime | Date.now() at the start of the original internal execution function | Baseline for durationMs; its definition is omitted in the excerpt |
The original template uses Webhook typeVersion: 2 and AI Agent typeVersion: 1. The excerpt below remains abbreviated; the mapping does not guarantee working input validation, AI Agent Prompt configuration, or Tool connections. Source locations: apps/api/src/domain/execution/execution.service.ts, packages/n8n-client/src/templates/agent-workflow.ts (private).
async execute(dto: CreateExecutionDto): Promise<ExecutionRecord> { // 1. Validate â Agent existence + active status const agent = await this.agentRepo.findById(dto.agentId); if (!agent) throw new NotFoundException(`Agent ${dto.agentId} not found`); if (agent.status !== 'active') { throw new BadRequestException(`Agent is not active (status: ${agent.status})`); }
// 2. Create execution record (pending) const execution = await this.executionRepo.create({ agentId: dto.agentId, input: dto.input, status: 'pending', });
// 3. Render prompt â variable substitution const variables = dto.input as Record<string, string>; const { text: rendered } = renderTemplate(agent.systemPrompt || '', variables); await this.logService.log(execution.id, 'render', 'Prompt rendered');
// 4. Deploy workflow (sequential reuse) const deployResult = await this.n8nService.deployAgent({ ... }); await this.logService.log(execution.id, 'deploy', `Workflow: ${deployResult.workflowId}`);
// 5. Execute via webhook const result = await this.n8nService.executeAgent(deployResult.webhookPath, message); await this.logService.log(execution.id, 'execute', 'Webhook executed');
// 6. Save result (completed) const durationMs = Date.now() - startTime; return this.executionRepo.update(execution.id, { status: 'completed', output: result, durationMs, });}The excerpt shows calls logging render, deploy, and execute, plus a completed update on success. It does not show per-step input/output persistence for validate or complete, or a transition to failed on exceptions, so those are not guaranteed here. Calls abbreviated with ... are not complete executable code.
Tech Stack
Section titled âTech Stackâ| Layer | Technology | Reason for choosing |
|---|---|---|
| Frontend | Next.js 16 | App Router, Server Components |
| Backend | NestJS | DI, Module system, TypeORM integration |
| Database | PostgreSQL 16 | Use of JSON columns (modelConfig, tools) |
| Workflow | n8n 1.94.1 | REST API, AI Agent node, Self-hosted |
| LLM | Gemini 2.5 Flash | Free Tier, fast response speed |
| Monorepo | pnpm workspace | sharing shared packages |
Project Structure (pnpm Monorepo)
Section titled âProject Structure (pnpm Monorepo)âDirectoryn8n-poc/
Directoryapps/
Directoryapi/ NestJS Backend (Port 3001)
Directorysrc/
Directorydomain/ Service + Port interfaces
- âŠ
Directoryinfrastructure/ TypeORM adapters, n8n integration
- âŠ
Directoryinterface/ Controllers
- âŠ
Directoryweb/ Next.js Frontend (Port 3000)
- âŠ
Directorypackages/
Directoryshared/ shared types, DTO, prompt utils, masking
- âŠ
Directoryn8n-client/ n8n REST API client + workflow template
- âŠ
Directorydocker/
- docker-compose.yml PostgreSQL + n8n
What I Learned from the n8n Integration
Section titled âWhat I Learned from the n8n IntegrationâDistinguish the n8n API contract from symptoms reported in one environment. The version recorded here is 1.94.1; the checks below use official source at that release tag and the 2.0 migration documentation. The exact patch version of the historical 2.x comparison and the requests/logs for the waiting/500 symptoms are unavailable, so they are not presented as reproduced results.
Webhook Paths Depend on Node Configuration
Section titled âWebhook Paths Depend on Node ConfigurationâPOST /webhook/{workflowId}/webhook/{userDefinedPath}This is not a fixed rule for all of 1.94.1. The original template named its node Webhook and did not set webhookId. In that case, 1.94.1âs getNodeWebhookPath() uses {workflowId}/{lowercase node.name}/{path}, yielding the form above. With webhookId and isFullPath true it uses the configured path alone; otherwise it uses {webhookId}/{path}. Dynamic paths also take a separate branch, so do not copy this URL into a different Workflow unchanged.
/webhook/ is the default production endpoint, distinct from the test URL. In 1.94.1, production calls require Workflow activation (Webhook node guidance). Compare the URL displayed by n8n with the Webhook node JSON and reverse-proxy/base-URL/endpoint configuration. The URL in the E2E diagram below is likewise an intended path specific to this PoC template.
Task Runners Are Not a Requirement for the AI Agent Itself
Section titled âTask Runners Are Not a Requirement for the AI Agent ItselfâN8N_RUNNERS_ENABLED: 'true' # Enable task runners; not an AI Agent requirement1.94.1âs TaskRunnersConfig defaults to false. Task runners execute code for Code nodes; they are not a switch enabling the AI Agent itself (official task runner explanation). The same releaseâs Tools Agent V1 execution code uses a Chat Model and LangChain executor. Do not equate runner requirements for Code nodes/code-based Tools with execution requirements for the Agent itself.
The earlier claim of âwaiting indefinitely without the settingâ does not establish that this variable is required. Without the request, AI Agent configuration, and logs, the cause remains unknown. Rather than treating this variable alone as a fix, check model credentials/connections, Prompt configuration, execution errors, and timeouts separately.
Publish in n8n 2.0 and Public API activate
Section titled âPublish in n8n 2.0 and Public API activateâThe 2.0 migration document replaces the UIâs Activate/Deactivate with Publish/Unpublish and separates a saved draft from the executing version. However, âan additional publish call is always needed after API activateâ is incorrect. In the verified 2.0.0 Public API, the activateWorkflow handler and Workflow service handle POST /api/v1/workflows/{id}/activate by setting the selected versionId (the current workflow.versionId if omitted) as activeVersionId and activating it. This endpoint therefore performs publication of the execution version.
The original PoC client also calls /api/v1/workflows/{id}/activate. When moving to 2.x, do not infer that an updated draft is executing from the active boolean alone; check the execution version and Webhook registration. Only the 2.0.0 source semantics were checked here, not the PoCâs 2.x compatibility or success/failure in the earlier comparison environment. The recorded 1.94.1 is a historical design reference, not a version recommendation for a new deployment.
Gemini Credential Type
Section titled âGemini Credential Typeâ1.94.1âs Google Gemini Chat Model node references the Google AI (Gemini) API key using the googlePalmApi credential type. Despite the Palm name, this node uses that type too. Verify the type name and credential ID separately.
Workflow Creation settings Contract and Error Status
Section titled âWorkflow Creation settings Contract and Error StatusâThe 1.94.1 Public API POST /api/v1/workflows Workflow schema marks name, nodes, connections, and settings as required. Including settings: {} when no settings are needed follows this API contract. The original clientâs create/update methods also build the payload with { settings: {}, ...workflow }.
However, âomitting it returns 500â is not a general rule. The same versionâs creation endpoint specification documents 400 for bad requests. The historical 500 remains an unconfirmed environment observation because the actual request body, response, and server logs are unavailable. Do not extend this required-field contract to the internal /rest API or every n8n version.
E2E Scope and Reproduction Criteria
Section titled âE2E Scope and Reproduction CriteriaâThe following is the intended path to verify. This article includes no reproducible run record, measurement environment, or failure-test result, so it does not establish an actual E2E success:
- Success path check: activate an Agent, execute it with anonymized input, then compare the API response and stored execution
completedstate/output by application execution ID. The n8n execution may have a separate ID; correlate it using workflow ID, timestamps, and logs rather than equating the two IDs. No such record is supplied here. - Response-time check: measure request start/end and
durationMsrepeatedly, recording distribution and environment. Without measurements, no specific number of seconds is claimed. - Log/failure check: inspect the DB for
render,deploy, andexecutelogs and sensitive-data masking. Inject a Webhook failure and separately test that the execution does not remainpendingbut transitions tofailedwith safe error information. The shown success-path code does not implement that failure transition.
Retrospective
Section titled âRetrospectiveâImplemented Scope and Open Verification
Section titled âImplemented Scope and Open Verificationâ| Hypothesis | What This Article Establishes |
|---|---|
| Does an Agent abstraction hold up on top of n8n? | Code and architecture map Prompt/Config to a Workflow; no execution result is supplied |
| Is the Prompt + Tool + Workflow model practical? | Tool listing/assignment exists, but the generated Workflow has no Tool connections; this PoC does not establish Tool execution |
| Is a minimal Builder UI feasible? | The UI structure is shown, but no working-run record is supplied |
What Was Intentionally Excluded
Section titled âWhat Was Intentionally Excludedâ- Multi-tenancy: a single-user PoC
- RBAC: no authentication/authorization
- Cost optimization: no token usage tracking
- Prompt versioning: no change history management
- Multi-Agent: collaboration/chaining between Agents
- Tool execution wiring: translate selected Tools to n8n nodes, credentials, and AI Agent connections and verify actual invocation
Next Steps
Section titled âNext StepsâBuilding on this PoC, in Integrating an AI Agent Builder with Backstage IDP I integrate it as a Backstage IDP plugin and build a structure for managing AI Agents in the organizationâs internal developer portal.
Source availability: The repository is not publicly accessible. This article includes only code excerpts with sensitive details removed; its code and diagrams are not substitutes for execution results.