Dev.to AI πŸ€– Ai πŸ‘ 0 πŸ“– 7 min read

Prompt Sourcing: Extending Event Sourcing to Generative AI

In modern core banking architectures built on Event Sourcing and Command Query Responsibility Segregation (CQRS), system state is derived entirely from an immutable sequence of domain events. When a traditional microserv

In modern core banking architectures built on Event Sourcing and Command Query Responsibility Segregation (CQRS), system state is derived entirely from an immutable sequence of domain events. When a traditional microservice processes a transaction, it records what state changed by appending discrete domain eventsβ€”such as AccountDebitedEvent or PaymentExecutedEventβ€”to an event store.

However, as core banking platforms integrate autonomous Large Language Model (LLM) agents to perform complex operational reasoning, traditional event sourcing reveals a critical compliance blind spot: The Black-Box Reasoning Gap.

When an AI agent approves a credit limit exception or waives an Anti-Money Laundering (AML) flag, simply logging the final business event (CreditOverrideApprovedEvent) records what happened, but completely obscures why it happened. If a regulatory audit or legal dispute occurs six months later, reconstructing the agent's exact decision path is impossible if the context window, prompt version, retrieved Retrieval-Augmented Generation (RAG) vector chunks, and intermediate tool-call iterations were not permanently captured.

Under the Xenon Architecture Standards, modern financial platforms resolve this auditability gap by introducing Prompt Sourcing. Prompt Sourcing extends traditional Event Sourcing to generative AI runtimes by treating every context window modification, system prompt update, RAG document injection, tool call, and completion token stream as an immutable, append-only event stream stored in high-throughput Apache Kafka audit topics and long-term WORM (Write Once, Read Many) cold storage.

πŸ’‘ Explore the Xenon Architecture Standard For comprehensive architectural blueprints, BIAN service domain mappings, and dual-orchestration integration patterns, visit the official Xenon Architecture Guide. To inspect reference code, infrastructure templates, and open-source banking modules, explore the VecPay-Tech GitHub Organization.

BIAN Service Domain Mapping & Prompt Event Taxonomy

In a Banking Industry Architecture Network (BIAN) ecosystem, prompt event emission must be categorized by domain criticality, context volatility, and regulatory retention mandates.

BIAN Service Domain AI Agent Capability Prompt Event Types Emitted Event Payload Scope Regulatory Retention SLA
Customer Advice Product suitability & portfolio analysis SystemPromptSet, RagChunkInjected, CompletionGenerated System instruction version, vector similarity scores, output tokens 7 Years (MiFID II / SEC)
Credit Assessment Commercial credit exception underwriting PromptContextAssembled, ToolCallInvoked, GuardrailEvaluated Input facts, financial ratio tokens, DMN guardrail diffs 10 Years (OCC / Basel III)
Fraud Evaluation Suspicious transaction triage ContextDeltaAppended, ModelInferenceLogged Real-time transaction window, anomaly confidence score 5 Years (AML / FATF)
Trade Positioning Unstructured document clause verification DocumentChunkInjected, ReasoningStepLogged OCR vector embeddings, clause reasoning traces 10 Years (CFTC / EMIR)

Mathematical Model: Prompt Context Reconstruction Lineage

To satisfy regulatory standards (such as BCBS 239 and EU AI Act Article 12 on Record-Keeping), a Prompt Sourced architecture must guarantee Point-in-Time Context Reconstructibility.

Let C(t) represent the complete context window memory state of an LLM agent at execution timestamp t . The context state C(t) is modeled as an ordered fold function over the sequence of all preceding prompt events e1​,e2​,…,en​ appended to the agent's event stream up to time t :

C(t)=i=1⨁n(t)​ei​=e1β€‹βŠ•e2β€‹βŠ•β‹―βŠ•en(t)​

Where βŠ• represents the context aggregation operator appending system instructions, RAG vector chunks, conversation history deltas, and tool execution observations into the active token window.

The lineage completeness score Llineage​ across M captured agent decision nodes is defined as:

Llineage​=k=1∏M​(1βˆ’Pmissing-event-k​)

Where Pmissing-event-k​ is the probability of a missing context event (e.g., an un-logged RAG document chunk or un-versioned system prompt). By mandating that the agent execution gateway writes prompt events synchronously to Kafka before model inference occurs, Pmissing-event​→0 , achieving Llineage​=1.0 (100% deterministic auditability).

Prompt Sourcing System Architecture Topology

The Prompt Sourcing architecture decouples Agent Token Execution from Asynchronous Audit Archiving, utilizing Kafka as the central event store backbone.

                           PROMPT SOURCING ARCHITECTURE TOPOLOGY

  +-----------------------------------------------------------------------------------+
  | AI AGENT RUNTIME & CONTEXT BUILDER                                                |
  |                                                                                   |
  |  [ RAG Vector Store ] ───► Assemble Context ───► [ LLM Inference Gateway ]       |
  |                                   β”‚                                               |
  +-----------------------------------|-----------------------------------------------+
                                      |
                     1. Synchronous Prompt Event Emission
                        (Transactional Outbox Pattern)
                                      |
                                      v
  +-----------------------------------------------------------------------------------+
  | APACHE KAFKA AUDIT INFRASTRUCTURE                                                 |
  |                                                                                   |
  |  Topic: `core.bian.prompt-sourcing.events.v1`                                     |
  |  Key:   `correlationId` (e.g., BIAN-CRED-2026-90128)                             |
  +-----------------------------------+-----------------------------------------------+
                                      |
            β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
            | 2a. Real-time Stream Analytics                    | 2b. Cold Storage Ingestion
            v                                                   v
  +-----------------------------------+               +-----------------------------------+
  | CLICKHOUSE / ELASTICSEARCH        |               | AWS S3 WORM ARCHIVE               |
  |                                   |               | (Object Lock / Compliance Mode)   |
  | [ Real-Time Token & Cost Audit ]  |               | [ Immutable 10-Year Audit Trail ] |
  +-----------------------------------+               +-----------------------------------+

Deep Dive Implementation: Event Schemas & Java Prompt Store

1. JSON Schema Specification: PromptContextAssembledEvent

Every prompt assembled by an AI agent is emitted as a structured, strongly typed event payload containing cryptographic hashes of system instructions, exact injected RAG document metadata, and token parameters.

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "eventId": "EVT-PRMPT-2026-881029",
  "eventType": "PromptContextAssembledEvent",
  "timestamp": "2026-09-16T14:30:00Z",
  "correlationId": "BIAN-CRED-2026-90128",
  "agentIdentity": "urn:xenon:agent:bian:credit-assessment",
  "modelParameters": {
    "provider": "Azure-OpenAI",
    "modelDeployment": "gpt-4o-financial-v2",
    "temperature": 0.0,
    "topP": 1.0,
    "maxTokens": 2048
  },
  "promptContext": {
    "systemInstructionHash": "sha256:7c98b6a12df49b95bc86d26210f5451e506822c678a876a3e201b124876b50bf",
    "systemInstructionVersion": "v2026.3.1",
    "injectedRagChunks": [
      {
        "vectorId": "vec-doc-8812-chunk-4",
        "documentName": "Commercial_Credit_Policy_2026.pdf",
        "similarityScore": 0.942,
        "contentSnippetHash": "sha256:a4f82b..."
      }
    ],
    "userPromptRaw": "Evaluate credit limit override for Account ACC-9012 for amount $75,000.",
    "tokenCountEstimated": 842
  }
}

2. Java 21 Prompt Sourced Agent Memory Engine

The Java implementation below demonstrates how an AI agent manager manages context memory by appending prompt events directly to Kafka, enabling point-in-time state reconstruction.

package com.xenon.banking.ai.promptsourcing;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutionException;

public record RagChunkMetadata(
        String vectorId,
        String documentName,
        double similarityScore,
        String contentSnippetHash
) {}

public record PromptEventPayload(
        String eventId,
        String eventType,
        String correlationId,
        String agentIdentity,
        String systemInstructionVersion,
        List<RagChunkMetadata> ragChunks,
        String userPrompt,
        String completionText,
        Instant timestamp
) {}

@Service
public class PromptSourcingMemoryManager {

    private final KafkaProducer<String, String> kafkaProducer;
    private final ObjectMapper objectMapper;
    private static final String TOPIC_NAME = "core.bian.prompt-sourcing.events.v1";

    public PromptSourcingMemoryManager(KafkaProducer<String, String> kafkaProducer, ObjectMapper objectMapper) {
        this.kafkaProducer = kafkaProducer;
        this.objectMapper = objectMapper;
    }

    public void appendPromptEvent(
            String correlationId,
            String agentIdentity,
            String systemVersion,
            List<RagChunkMetadata> ragChunks,
            String userPrompt,
            String completionText) {

        PromptEventPayload event = new PromptEventPayload(
                "EVT-" + UUID.randomUUID(),
                "PromptInferenceCycleCompletedEvent",
                correlationId,
                agentIdentity,
                systemVersion,
                ragChunks,
                userPrompt,
                completionText,
                Instant.now()
        );

        try {
            String jsonEvent = objectMapper.writeValueAsString(event);

            // Synchronous write to Kafka to enforce write-before-execution guarantee
            ProducerRecord<String, String> record = new ProducerRecord<>(TOPIC_NAME, correlationId, jsonEvent);
            record.headers().add("X-BIAN-Domain", "CreditAssessment".getBytes());
            record.headers().add("X-Event-Type", "PromptInferenceCycleCompletedEvent".getBytes());

            kafkaProducer.send(record).get(); // Blocks until acknowledged by quorum broker

            System.out.println("Prompt event successfully appended to Kafka. EventID: " + event.eventId());

        } catch (Exception e) {
            // Fail-Closed: If prompt event cannot be persisted to Kafka, block AI execution
            throw new IllegalStateException("CRITICAL COMPLIANCE FAILURE: Unable to persist Prompt Event to Kafka.", e);
        }
    }
}

Point-in-Time Context Replay & Regulatory Auditing

When financial regulators (such as OCC, EBA, or MAS) demand an explanation for an automated AI decision made months earlier, compliance officers execute a Prompt Event Replay.

The replay worker queries Kafka or cold S3 storage for the correlation ID, retrieves the sequence of prompt events, and reconstructs the exact context window visible to the model at that millisecond:

package com.xenon.banking.ai.promptsourcing;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PointInTimePromptReplayService {

    private final JdbcTemplate jdbcTemplate;
    private final ObjectMapper objectMapper;

    public PointInTimePromptReplayService(JdbcTemplate jdbcTemplate, ObjectMapper objectMapper) {
        this.jdbcTemplate = jdbcTemplate;
        this.objectMapper = objectMapper;
    }

    public ReconstructedContextWindow reconstructContextAsOf(String correlationId, String targetTimestamp) {
        String sql = """
            SELECT payload FROM prompt_events_archive 
            WHERE correlation_id = ? AND created_at <= ?::timestamptz 
            ORDER BY created_at ASC
            """;

        List<PromptEventPayload> eventSequence = jdbcTemplate.query(
                sql,
                (rs, rowNum) -> {
                    try {
                        return objectMapper.readValue(rs.getString("payload"), PromptEventPayload.class);
                    } catch (Exception e) {
                        throw new RuntimeException("Error deserializing prompt event", e);
                    }
                },
                correlationId,
                targetTimestamp
        );

        // Fold event sequence to reconstruct identical token context window
        StringBuilder contextBuilder = new StringBuilder();
        for (PromptEventPayload event : eventSequence) {
            contextBuilder.append("[").append(event.eventType()).append("]\n");
            contextBuilder.append("System Version: ").append(event.systemInstructionVersion()).append("\n");
            contextBuilder.append("RAG Context Count: ").append(event.ragChunks().size()).append("\n");
            contextBuilder.append("User Prompt: ").append(event.userPrompt()).append("\n");
            contextBuilder.append("Model Output: ").append(event.completionText()).append("\n");
            contextBuilder.append("--------------------------------------------------\n");
        }

        return new ReconstructedContextWindow(correlationId, targetTimestamp, contextBuilder.toString());
    }

    public record ReconstructedContextWindow(String correlationId, String timestamp, String fullContextText) {}
}

Operational Strategies: Payload Bloat & Storage Management

Storing every prompt context window in Kafka can introduce payload bloat if context sizes reach hundreds of kilobytes per inference cycle. To maintain streaming performance, modern architectures apply two operational patterns:

1. The Claim-Check Pattern for Large RAG Vectors

If a RAG retrieval returns multi-megabyte document context chunks, the event payload written to Kafka stores only the Claim Check Reference (e.g., S3 URI + SHA-256 hash of the retrieved chunk) rather than embedding raw text in the message payload. During an audit replay, the replay engine hydrates the raw text directly from the immutable S3 object lock store.

2. Zero-Data-Retention (ZDR) Model Gateways

To ensure compliance with data privacy regulations (such as GDPR and HIPAA), Prompt Sourced event streams must redact personally identifiable information (PII) using automated masking filters before writing to Kafka. Furthermore, external AI API gateways must enforce Zero Data Retention (ZDR) agreements, ensuring third-party LLM providers never store or train on transmitted financial prompts.

Extending Event Sourcing to Generative AI via Prompt Sourcing eliminates the black-box opacity of autonomous decision nodes. By persisting system prompts, RAG document retrievals, tool invocations, and completion streams as immutable events in Kafka, modern core banking architectures achieve complete point-in-time explainability, robust AI governance, and strict regulatory compliance across all BIAN service domains.

πŸ“° Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.