Skip to content

Design and Implementation of an n8n-based AI Agent Builder

Interactive Diagram

새 탭 ↗

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?”


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.
PlantUML Diagram

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.

Considerationn8nLangChain/LangGraphCustom build
Workflow visualization✅ Built-in❌❌
AI Agent node✅ Built-in✅Build it yourself
Tool integration (Slack, HTTP, etc.)✅ 400+SDK-basedBuild it yourself
Self-hosted✅✅✅
REST API✅❌Build it yourself
Learning curve (user)HighVery highLow

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.


I applied the Layered Architecture pattern of Domain-Driven Design:

PlantUML Diagram

In the Domain layer, the Repository Port is defined as a pure TypeScript interface. There is no framework dependency at all:

domain/agent/agent.interface.ts
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');

The Service accesses data only through the Port. The NestJS DI container injects the Adapter via @Inject(AGENT_REPOSITORY):

domain/agent/agent.service.ts
@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' });
}
}

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:

infrastructure/database/entities/agent.entity.ts
@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;
}

The NestJS Module binds the Port and the Adapter:

@Module({
providers: [
AgentService,
{ provide: AGENT_REPOSITORY, useClass: AgentRepositoryImpl },
],
})
export class AgentModule {}

The target Agent abstraction has three elements, but the execution path shown in the code below covers Prompt and Config:

ElementDescriptionExample
PromptSystem prompt + variable template"You are a {{role}}"
Tool (extension)Storing/selecting IDs is distinct from wiring n8n Tool nodesHTTP Request, Slack, Calculator are candidates, not connected examples
ConfigModel 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.

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.

PlantUML Diagram

The TypeScript excerpt shows how a Chat Model node is created for each LLM Provider. This branch does not create Tool nodes:

packages/n8n-client/src/templates/agent-workflow.ts
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:

infrastructure/n8n/n8n-integration.service.ts
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.

Agent execution consists of a 6-stage pipeline. The ExecutionService orchestrates the entire flow:

PlantUML Diagram

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.

ValueConfirmed Data PathMeaning and Limit
dto.inputStored as execution input and used as variables for renderTemplate(agent.systemPrompt, variables)as Record<string, string> is a type assertion, not runtime input validation
rendereddeployAgent({ systemPrompt: rendered, ... }) → buildAgentWorkflow() → AI Agent parameters.options.systemMessageAI Agent system prompt; the original also stores it as renderedPrompt
messagedto.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 bodyAI Agent text: '={{ $json.body.message }}'Expression for the user Prompt; actual evaluation/model response remains unverified
startTimeDate.now() at the start of the original internal execution functionBaseline 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).

domain/execution/execution.service.ts
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.


LayerTechnologyReason for choosing
FrontendNext.js 16App Router, Server Components
BackendNestJSDI, Module system, TypeORM integration
DatabasePostgreSQL 16Use of JSON columns (modelConfig, tools)
Workflown8n 1.94.1REST API, AI Agent node, Self-hosted
LLMGemini 2.5 FlashFree Tier, fast response speed
Monorepopnpm workspacesharing shared packages
  • 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

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.

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”
docker-compose.yml
N8N_RUNNERS_ENABLED: 'true' # Enable task runners; not an AI Agent requirement

1.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.

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.

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.

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.


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:

PlantUML Diagram
  • Success path check: activate an Agent, execute it with anonymized input, then compare the API response and stored execution completed state/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 durationMs repeatedly, recording distribution and environment. Without measurements, no specific number of seconds is claimed.
  • Log/failure check: inspect the DB for render, deploy, and execute logs and sensitive-data masking. Inject a Webhook failure and separately test that the execution does not remain pending but transitions to failed with safe error information. The shown success-path code does not implement that failure transition.

HypothesisWhat 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
  • 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

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.