Skip to main content
Version: devel View Markdown

Background agents

info

This feature is in public preview

An agent job is a dltHub job that runs an AI agent loop, the building block of background agents. It runs unattended on a schedule, after another job fails, or when you start it from the CLI or the Web UI. It reads what you let it read, and it returns a structured result that shows on the page of each entity that it acted on.

Three terms are used on this page:

  • An agent definition is the system prompt plus a declaration of the inputs, the output, the tools, and the access of the agent. You write it as an AGENT.md file or as a decorated Python function.
  • An agent job is a definition plus the settings of your workspace: trigger, model, limits. You declare it with run.agent(...) in __deployment__.py.
  • An agent run is one execution of the agent job. It receives inputs and returns an agent output and an agent trace.

Agent jobs are declared, run, and deployed like every other job. This page shows the common tasks, one example each: build an agent, customize an installed one, validate it, test it, limit what it can touch, and control what a run costs. The Agent definition reference covers every field and argument. The job inspector agent is a complete agent definition that the dlthub-platform toolkit ships.

Prerequisites​

  1. A dltHub workspace with dlt[hub] installed and connected to the platform. See Workspace setup.

  2. An agent loop installed for local runs. On the platform, the runner installs the loop of the job:

    uv add "pydantic-ai-slim[anthropic,openai,google,mcp,spec]"   # pydantic-ai loop (default)
    uv add claude-agent-sdk # claude-agent-sdk loop
  3. A model and its API key, in the [agent] section of the workspace configuration: the model in .dlt/config.toml, the key in .dlt/secrets.toml. Local and deployed runs read the same files. See Model and credentials.

Build an agent with an AGENT.md​

An AGENT.md holds the declarations in its YAML frontmatter, and its Markdown body is the system prompt. This agent reads the status of every job in the workspace and writes a report:

---
description: Reports the latest status of every job in the workspace. Read-only.
tools: [jobs]
access:
context: [read]
output:
type: object
properties:
jobs_total: { type: integer }
failed_jobs: { type: array, items: { type: string } }
---
List every job in the workspace and read the status of its latest run. Report
how many jobs there are and which ones failed. In `summary`, write a Markdown
table with one row per job: name, last run status, and when it ran.

Save it as agents/workspace_report/AGENT.md and declare the agent job by its folder in __deployment__.py:

from dlt.hub import run

workspace_report = run.agent("agents/workspace_report", trigger="schedule:0 7 * * *")

__all__ = ["workspace_report"]

Run it once locally, then deploy:

dlthub local run workspace_report
dlthub deploy
  • Only the body is required. A file with no frontmatter is a working agent definition, named after its folder.
  • An agent definition that a toolkit installed is referenced as <toolkit>:<name>, for example "dlthub-platform:job-inspector".
  • See Agent definition in an AGENT.md file for every field.

Customize an existing agent​

An agent definition that a toolkit installed is a starting point. The agent job changes what the definition declares, with no copy and no function:

from dlt.hub import run

inspector = run.agent(
"dlthub-platform:job-inspector",
trigger="job.fail:tag:ingest",
access={"local": ["read"], "context": ["read"], "data": ["read"]},
skills=[
"dlthub-platform:debug-workspace-deployment",
".claude/skills/our-runbook/SKILL.md",
],
instructions="Our ingest jobs load into Snowflake. Check the warehouse first.",
limits={"max_turns": 20},
)
  • access, tools, skills, and rules replace the lists of the definition as a whole. Name every axis and every skill that the agent still needs, and leave an argument out to keep what the definition declares.
  • instructions is the first user message of each run: put the task of your workspace there. model, limits, loop_run_args, and execute override the defaults of the definition.
  • The definition keeps its system prompt, inputs, output, and agent.py, and it follows the updates of its toolkit. To change the system prompt, copy the folder into your workspace and refer to it by its path, or drive the definition from a decorated function with a docstring.

See Agent job arguments.

Validate inputs and outputs with agent.py​

An agent.py next to the AGENT.md runs code before and after the loop. validate_input gets the inputs before the first turn, and validate_output gets the agent output after the last one. This agent requires a run id and refuses a success without evidence:

# agents/run-inspector/agent.py
from dlt.hub.run import JobAbortedException


def validate_input(inputs):
run_id = inputs.get("failed_run_id")
if not run_id:
# ends the run without calling the model
raise JobAbortedException("no failed run to inspect", {"summary": "nothing to inspect"})
return {**inputs, "failed_run_id": run_id.strip()}


def validate_output(output):
if output["status"] == "succeeded" and not output.get("evidence"):
return {**output, "status": "failed", "summary": "the diagnosis cites no evidence"}
return None
  • Return the whole dict, or None to keep it as it is. inputs also holds run_context.
  • dlt runs agent.py only for a job that references the agent definition. A decorated function runs its own code instead.
  • See Agent code in agent.py.

Build a fully custom agent​

A decorated function is an agent definition without an AGENT.md. The docstring is the system prompt, the parameters with a default are the inputs, and the return type is the output. The function drives the loop, so it can run code around it:

from typing import Annotated, Literal

from dlt.hub import run


class CrashReport(run.TAgentOutput):
"""Diagnosis of one failed job run."""
classification: Literal["config", "credentials", "code", "upstream_data", "unknown"]
confidence: Literal["high", "medium", "low"]


@run.agent(
access={"local": ["read"], "context": ["read"]},
tools=["jobs", "logs"],
trigger="job.fail:tag:ingest",
)
async def crash_inspector(
failed_run_id: Annotated[str, run.Entity("job-runs")] = None,
run_context: run.TJobRunContext = None,
) -> CrashReport:
"""Inspect a failed job run and report a diagnosis.

You run unattended, seconds after a job failed. Explain the failure; do not repair it.
Investigate run '{{ failed_run_id }}' from `{{ run_context.trigger }}`.
"""
loop = run_context["ai_loop"]
report = await loop.run(inputs={"failed_run_id": failed_run_id})
if loop.trace["total_tokens"] > 800_000:
report["summary"] += "\n\n_Expensive run: narrow the trigger._"
return report

A function can also drive an installed agent definition: pass it as agent="<toolkit>:<name>". The definition keeps its system prompt and its output, and your function runs code around the loop. To change only the access, the skills, or the settings of an installed agent, you need no function: see Customize an existing agent. See Agent definition as a Python function.

Test agent jobs​

An agent job is a function: it takes inputs and returns a value. You test it like other Python code:

import pytest

from my_agents import crash_inspector


@pytest.mark.asyncio
async def test_crash_inspector() -> None:
run_context = {"run_id": "r-test", "trigger": "job.fail:jobs.ingest", "refresh": False}

report = await crash_inspector(failed_run_id="r-failed-42", run_context=run_context)

assert report["status"] == "succeeded"
job_result = crash_inspector.last_job_result
assert {"type": "job-runs", "id": "job-runs/r-failed-42"} in job_result["object"]
assert "Bash" not in job_result["trace"]["tools_used"]
assert job_result["trace"]["total_tokens"] < 200_000
  • Await an agent job without a function and an async def decorated function. Call a sync decorated function without await.
  • Pass the inputs as keyword arguments and a run_context with the trigger that you test. Without run_context, the run gets the trigger manual:.
  • last_job_result holds the job result of the call: the agent output, the agent trace, and the entities. dlt sends nothing to the platform. Mock the APIs that your agent.py or your function calls, as in any other test.

Sandbox the agent with access​

access declares what the agent may touch, per axis. The model is offered only the tools that the declared access covers:

access:
local: [read] # Read, Glob, Grep on the workspace files
context: [read] # runs, logs, job definitions, telemetry through the dltHub MCP server
data: [read] # the data in your destinations; SQL is limited to one SELECT

The data axis also selects the profile of the job, and with it the credentials that its process holds:

data in accessProfile in the prod environment
left outno-access, a profile without data access
readaccess
writeprod
  • Leave out every axis and verb the task doesn't need. local: [execute] gives the agent a shell that runs with the credentials of the job, so declare it only when there is no other way.
  • Credential files (*secrets.toml, .env) are never readable by a file tool, whatever local declares.
  • An agent job can replace the access of its definition: run.agent("<toolkit>:<name>", access=...). The argument replaces the whole block, so name every axis. See Customize an existing agent.
warning

Make the credentials of the access profile read-only at the destination, for example with a read-only database role. dltHub doesn't check what a credential can do. Create the settings files of access before you deploy: without them, an agent job that declares data: read gets prod.

See Access declaration, Profile of an agent job, and Guardrails.

Give the agent skills and rules​

Skills and rules are components of an installed toolkit, referenced as <toolkit>:<name>, or files referenced by their workspace-relative path:

tools: [jobs, logs, telemetry]
skills:
- dlthub-platform:debug-workspace-deployment
- .claude/skills/my-runbook/SKILL.md
rules:
- agents/rules/read-only.md
  • The agent sees the name and the description of each skill and loads a skill when it needs it. With local: read, it can also read the files next to the SKILL.md.
  • A rule is inlined into the system prompt, so it costs tokens on every turn. Keep rules short.
  • The agent gets only the components that you list. A reference that doesn't resolve is skipped and logged as info, so a skill from a toolkit that the workspace didn't install is optional.
  • Skills written for a person at a terminal tell the agent to run commands. Say in the body that the agent has no shell and no user.

See Tools, skills, and rules.

Use structured input and output​

inputs and output are JSON Schemas. Every input becomes a configuration key of the job, and the output is the structured answer of the agent:

---
tools: [telemetry]
access:
context: [read]
inputs:
type: object
properties:
pipeline_name:
type: string
description: the pipeline to check
required: [pipeline_name]
output:
type: object
properties:
verdict:
type: string
enum: [pass, warn, fail]
description: pass when every run of the week loaded rows, warn when one did not, fail otherwise
runs_checked:
type: integer
description: how many pipeline runs you read, between 1 and 100
required: [status, summary, verdict]
---
Check the pipeline runs of '{{ pipeline_name }}' over the last seven days, from trigger
`{{ run_context.trigger }}`. ...
  • Set an input with -c pipeline_name=..., in config.toml, or from the trigger. The body refers to it as {{ pipeline_name }}, and to the run as {{ run_context.trigger }}, {{ run_context.run_id }}, {{ run_context.profile }}, and the other keys of the run context. An optional input without a value renders as empty text, so say in the body what to do then.
  • Every output has status (succeeded, failed, aborted) and summary. Define in the body when each status applies. Put a domain outcome such as verdict in a field of its own.
  • Give every property a type, and define each enum value in the body. Put a numeric bound in the description: Anthropic rejects minimum and maximum. Keep the output schema under about 8,000 characters.

See Input schema and Output schema.

Use platform entities as inputs and outputs​

An input or output that names a workspace object carries entity_type: job-runs, job, pipeline, dataset, or workspace. The agent receives the bare id, such as a run id or a job ref:

inputs:
type: object
properties:
failed_run_id:
type: string
entity_type: job-runs
output:
type: object
properties:
failed_run_id: # the run the agent actually inspected
type: string
entity_type: job-runs
required: [status, summary, failed_run_id]

In a decorated function, write failed_run_id: Annotated[str, run.Entity("job-runs")] = None.

  • The job result lists the entities in object, so the agent run shows on the page of each entity in the Web UI.
  • The first entity-typed input links the agent job to its entity: on the row of a job run, the Web UI offers the agent and opens its latest run.
  • An output with the same name overwrites the input. An agent that resolved a run from a job ref reports the run it inspected. Keep such an output in required.

See Entity-typed inputs and outputs.

Control the agent budget​

limits caps a run. The loop ends the run when either limit is reached:

defaults:
limits: {max_turns: 30, max_tokens: 1000000}
execute: {timeout: 10m, concurrency: 3}

The job overrides the definition with limits={"max_turns": 20}, and one run overrides both with -c agent.max_turns=10.

  • A turn is one model request. max_tokens counts input tokens, cache reads and writes included, and output tokens over the whole run.
  • Every turn sends the system prompt and the history again, so the cost grows with the number of turns. Read turn_count and total_tokens in the agent trace, and size max_turns times the tokens of one turn under max_tokens.
  • A run that reads until the limit returns nothing. Tell the agent in the body when to stop reading and write its answer, for example after half of max_turns. Also give a page size for every list tool, because each result is sent again on every later turn.
  • Keep the prompt small. A rule costs its full text on every turn, a skill only its description until the agent loads it.
  • execute sets the timeout of a run and how many runs go at once. An agent job runs up to 5 runs at once by default.

See Defaults for the agent job.

Run and deploy​

Run an agent job locally with its inputs, and deploy it with the rest of the workspace:

dlthub local run job_inspector -c failed_run_id=<run_id>   # one local run
dlthub deploy # ships the job graph and the agent definitions

A trigger starts the agent job on the platform. job.fail: and job.success: react to other jobs: trigger="job.fail:tag:ingest" starts the agent job whenever a job tagged ingest fails. Without trigger=, the agent job runs only when you start it.

warning

Don't let two agent jobs watch job.fail:*. It matches agent jobs too, so a failed run of one starts the other, and the two jobs start each other until you archive one. Scope each agent job with a tag, a section, or job.fail:pipeline_name:*.

Next steps​

This demo works on codespaces. Codespaces is a development environment available for free to anyone with a Github account. You'll be asked to fork the demo repository and from there the README guides you with further steps.
The demo uses the Continue VSCode extension.

Off to codespaces!

DHelp

Ask a question

Welcome to "Codex Central", your next-gen help center, driven by OpenAI's GPT-4 model. It's more than just a forum or a FAQ hub – it's a dynamic knowledge base where coders can find AI-assisted solutions to their pressing problems. With GPT-4's powerful comprehension and predictive abilities, Codex Central provides instantaneous issue resolution, insightful debugging, and personalized guidance. Get your code running smoothly with the unparalleled support at Codex Central - coding help reimagined with AI prowess.