Skip to main content
connic
Back to BlogTutorial

How to Trigger AI Agents from Kafka Topics

Point a connic Kafka inbound connector at a topic and every message starts an agent run. Configure the connector, link an agent, deploy, and watch runs.

July 12, 2026(last updated: July 19, 2026)8 min readAuthor: Simon Dabrowski

Transactions, orders, and telemetry already flow through Kafka. The missing piece is an AI agent that reacts to them: scores the transaction, triages the alert, updates the recommendation. connic does not require a separate consumer service for that. A Kafka inbound connector points at the topic, and every message starts an agent run with the payload attached. This tutorial walks through the whole setup, from scaffolding a project to watching the first run.

Why Kafka Is a Strong Agent Trigger

Kafka is a durable, ordered log. Triggering agents from it provides at-least-once delivery, ordering within a partition, and the ability to replay history by resetting a consumer to an earlier offset, guarantees a plain HTTP webhook cannot make. The connector joins the cluster as a consumer, so there is no polling loop, no middleware service, and no bot process to keep alive between Kafka and the agents. Our trigger comparison covers webhook, Kafka, Postgres, and SQS. This post focuses on the implementation with Kafka.

  1. Scaffold a Project from the Template

    Prerequisites
    • Python 3.11+ installed
    • A reachable Kafka cluster with a topic to consume (this tutorial uses transactions)
    • A connic project connected to a Git repository
    • The template pins an Anthropic model, so either add an Anthropic key in Project Settings or switch the agent YAML to an exact connic/* model and use Project credit

    The fastest follow-along path is the Kafka Fraud Detector template from the connic Marketplace: a working project that consumes transactions from a Kafka topic and scores each one for fraud risk, with an escalation agent for high-risk cases. Install the SDK and scaffold from it:

    terminal
    pip install connic-composer-sdk
    connic init my-project --templates=kafka-fraud-detector
    cd my-project

    This creates a complete, deployable structure:

    file tree
    my-project/
      agents/
        kafka-fraud-detector/
          fraud-scorer.yaml
          fraud-escalator.yaml
      tools/
        fraud_tools.py
      middleware/
        fraud-scorer.py
      hooks/
        fraud-scorer.py
      schemas/
        fraud-assessment.json
      tests/
      requirements.txt

    Two agents, plain Python tools, middleware that flags admin requests, a hook that enforces the admin override, an output schema, and a test suite that runs with connic test. The Kafka Fraud Detector template includes the architecture diagram. Other Marketplace agent templates cover use cases beyond fraud scoring. Everything below works the same for an agent written from scratch.

  2. Look at the Agent YAML

    Each YAML file under agents/ defines one agent. Here is the scorer from the template, with the system prompt shortened:

    agents/kafka-fraud-detector/fraud-scorer.yaml
    version: "1.0"
    
    name: fraud-scorer
    type: llm
    model: connic/gpt-5.6-terra
    description: "Scores transactions for fraud risk in real-time from a Kafka stream"
    
    system_prompt: |
      You are a fraud detection specialist analyzing financial transactions in
      real-time from a Kafka stream.
    
      Use _kafka.key for customer correlation and _kafka.timestamp to detect
      processing latency.
    
    temperature: 0.1
    output_schema: fraud-assessment
    
    concurrency:
      key: "data.customer_id"
      on_conflict: queue
    
    tools:
      - fraud_tools.calculate_velocity
      - fraud_tools.check_geo_anomaly
      - fraud_tools.create_alert
      - fraud_tools.search_fraud_patterns
      - fraud_tools.store_fraud_pattern
      - fraud_tools.admin_override: context.is_admin == True

    For Kafka workloads, the prompt tells the model to use _kafka.key and _kafka.timestamp, metadata the connector attaches to every message. The concurrency block queues runs that share a customer_id, so two transactions from the same customer never race each other while the rest of the stream processes in parallel. And the last tool entry is conditional: admin_override only exists for the model when middleware has set is_admin in the run context. The agent configuration reference covers the full set of options.

  3. Deploy

    Push the project to the environment's deployment branch, and connic builds and deploys it automatically. Or deploy straight from the CLI:

    terminal
    connic login
    connic deploy

    While iterating, connic dev provides a hot-reloading dev server for adjusting the prompt and tools before wiring up production traffic.

  4. Create the Kafka Inbound Connector

    Connectors are created in the dashboard and linked to agents there. Open the fraud-scorer agent's detail page, click Add inbound connector on the Connector Flow, choose Create New Connector, and select Apache Kafka. The brokers and security settings live on a reusable Connection: under Connection, pick a saved one or create it. The topic and consumer settings go on the connector. For the tutorial setup:

    SettingValueNotes
    ModeInbound (Consumer)Consumes messages and triggers runs
    Bootstrap serverskafka:9092On the Connection. Comma-separated broker addresses, reachable from connic
    Security protocolPLAINTEXTOn the Connection. Or SSL, SASL_PLAINTEXT, SASL_SSL
    SASL mechanismPLAIN, SCRAM-SHA-256, or SCRAM-SHA-512On the Connection, plus username and password. SASL only
    TopictransactionsThe topic to consume from
    Consumer Group IDfraud-detectorOptional; auto-generated if left empty
    Auto offset resetlatestUse earliest to replay from the beginning

    The connector consumes from our infrastructure, so the brokers must be reachable from connic, directly or through bridge: a managed endpoint works out of the box, and a private cluster connects through bridge, covered at the end of this post. For managed Kafka, use SASL_SSL with the mechanism your provider supports: PLAIN with an API key and secret on Confluent Cloud, SCRAM-SHA-512 on Amazon MSK, and PLAIN, SCRAM-SHA-256, or SCRAM-SHA-512 on Aiven with SASL enabled. Mutual TLS is supported by pasting the CA certificate, client certificate, and client key PEM contents directly into the Connection; local file paths for certificates are not accepted. Once created, the connector is linked to the agent automatically and starts consuming.

    Consumer groups retain Kafka's standard behavior: connectors with different group IDs each receive every message, connectors sharing a group ID split the load. The connector tracks offsets, reconnects with exponential backoff, and picks up configuration changes without redeploying the agent.

    What the Agent Receives

    JSON messages arrive with their top-level fields intact, plus a _kafka block carrying topic, partition, offset, timestamp, and key:

    message-payload.json
    {
      "transaction_id": "tx-9917",
      "customer_id": "cust-1042",
      "amount": 4899.0,
      "currency": "EUR",
      "merchant": "TechWorld Berlin",
      "country": "DE",
      "_kafka": {
        "topic": "transactions",
        "partition": 0,
        "offset": 1542,
        "timestamp": 1705312800000,
        "key": "cust-1042"
      }
    }

    Non-JSON messages are wrapped under a message key, and compaction tombstones still trigger runs with message: null, so an agent can react to deletions via _kafka.key. The full payload behavior is in the Kafka connector reference.

  5. Publish Results Back to a Topic

    Downstream systems usually want the agent's verdict on a stream of their own. Repeat the connector setup on the same fraud-scorer agent, this time choosing Outbound (Producer) mode with fraud-alerts as the topic. Every time the agent completes a run, its structured assessment is published with the run ID, agent name, status, and output. Failed and cancelled runs are skipped. If the run was triggered by an inbound Kafka message with a key, the outbound message reuses the same key, so per-customer ordering survives the round trip through the agent.

  6. Send a Test Event and Watch the Run

    Produce a keyed test message to the topic:

    terminal
    kafka-console-producer \
      --bootstrap-server kafka:9092 \
      --topic transactions \
      --property parse.key=true \
      --property key.separator=:
    >cust-1042:{"transaction_id":"tx-9917","customer_id":"cust-1042","amount":4899.0,"currency":"EUR","merchant":"TechWorld Berlin","country":"DE"}

    Within moments a new run appears in the project's Runs section, with the full trace: the incoming payload, every tool call the scorer made, and the structured risk assessment it returned. The trace documentation explains how to read those traces. From here the loop is tight: adjust the prompt or tools, push, and the next message on the topic exercises the new version.

Private Kafka Clusters

Brokers on a private network do not need public exposure. Run connic bridge inside the private network and select it as the bridge on the Kafka Connection. Every connector that uses the Connection then reaches the brokers through a secure outbound tunnel.

Start with a working Kafka pipeline

The Kafka Fraud Detector template ships two agents, tools, middleware, schemas, and tests that you scaffold with one command and adapt to your own logic.

The connector also works for content moderation, personalization, and anomaly detection streams. The Marketplace describes the Kafka connector capabilities.

Frequently Asked Questions

Create a Kafka inbound connector in connic, point it at the topic with the bootstrap servers and optional SASL or SSL settings, and link it to a deployed agent. The connector joins the topic as a consumer and starts an agent run for every message, with the payload and Kafka metadata attached. No consumer code is required.

Yes. Set auto offset reset to earliest on a fresh consumer group and the connector processes the topic from the beginning, which is useful for reprocessing history after improving an agent. Delivery is at-least-once, so make the agent idempotent, for example by deduplicating on the Kafka message key.

Yes. Add a Kafka outbound connector and link it to the agent. Completed runs are published to the configured topic with the run ID, agent name, status, and output; failed and cancelled runs are skipped. Results triggered by a keyed inbound message reuse the same key, preserving partition ordering.

Yes. Use SASL_SSL as the security protocol. On Confluent Cloud, choose PLAIN and enter an API key and secret as username and password. On Amazon MSK, choose SCRAM-SHA-512 with the user from the cluster's SASL/SCRAM secret. For mutual TLS, paste the CA certificate, client certificate, and client key PEM contents directly into the Kafka Connection; local file paths are not supported.