Back to Templates

Run a margin-aware paid AI agent with Alephant x402 and Discord

Created by

Created by: alephantAI || alephant-ai
alephantAI

Last update

Last update 10 hours ago

Categories

Share


Quick Overview

This workflow exposes a paid webhook endpoint, verifies budget via Alephant usage analytics, routes the request through an OpenAI-based agent to pick the most cost-effective model, runs the chosen model through Alephant for cost tracking, then returns results with per-call margin reporting to Discord and optional throttling.

How it works

  1. Receives a POST request on a webhook endpoint that is intended to be paid per call over x402.
  2. Checks current budget status using Alephant Usage analytics and returns a 402-style JSON error response if the workspace budget is exceeded.
  3. Sends the buyer request and budget context to an OpenAI-based routing agent (via Alephant) that calls Alephant UsageSummary and outputs strict JSON selecting a model tier and refined prompt.
  4. Runs the refined prompt on the chosen model using Alephant AI to capture per-call usage and cost metadata.
  5. Calculates per-call profit and margin percentage from fixed revenue, token usage, and an Alephant fee estimate.
  6. Responds to the webhook caller with the model result plus net margin metrics, posts the margin line to Discord, and calls a policy write-back HTTP endpoint to throttle if margin drops below 20%.

Setup

  1. Install the Alephant community nodes and create an Alephant Virtual Key credential in n8n.
  2. Create an OpenAI credential that uses Base URL https://ai.alephant.io/v1 with your Alephant virtual key as the API key, and select it for the agent’s language model.
  3. Configure a Discord Webhook credential and set it on the Discord node used for the margin feed.
  4. Update the Per-Call P&L constants (price per call, token rate per 1k, external spend, and fee percentage) to match your real unit economics.
  5. Replace https://ai.alephant.io/REPLACE_WITH_POLICY_ENDPOINT with your real policy/throttling endpoint and set the ALEPHANT_API_KEY environment variable used for the Authorization header.
  6. Copy the webhook URL for the paid endpoint and configure your x402 buyer/agent to call this endpoint with the expected request body fields (for example, topic and runId).