Agents reference
================

Reference for agent-related functions, views, and types. For guide-style
documentation, see :ref:`Agents reference <Agents reference>`  .

Catalog views
-------------

aidb.agents
^^^^^^^^^^^

Agent configuration. There’s no dedicated “list agents” function — query
this table directly.

.. csv-table::
  :header: Column,Type,Description
  :widths: 12,15,25
  :align: left
  :class: longtable

  `id`,uuid,Internal identifier.
  `name`,text,Unique agent name.
  `instructions`,text,The agent's instructions.
  `model`,text,The model backing the agent.
  `role`,text,"Postgres role the agent's tool calls execute as, if configured."
  `delegates`,text[],Names of agents this agent may delegate to.
  `tools`,text[],Names of tools this agent may call.
  `output_type`,jsonb,"Structured output schema, built with `aidb.output_type()`."
  `input_token_budget`,integer,Input token budget per call.
  `output_token_budget`,integer,Output token budget per call.
  `max_iterations`,integer,Maximum reasoning iterations per call.
  `timeout_seconds`,integer,Maximum wall-clock time per call.
  `budget_strategy`,`aidb.budget_strategy`,Behavior when a budget is exceeded. See  :ref:`Types<Types>`  below.
  `preset`,text,"Stored, but not currently resolved to any behavior."
  `created_at`,timestamptz,Creation time.
  `updated_at`,timestamptz,Last update time.

aidb.agent_tasks
^^^^^^^^^^^^^^^^

One row per ``agent_converse`` call (a “task”), including its lifecycle
status.

.. csv-table::
  :header: Column,Type,Description
  :widths: 12,15,25
  :align: left
  :class: longtable

  `task_id`,uuid,Internal task identifier.
  `agent_id`,uuid,The agent that ran this task (`aidb.agents.id`).
  `conversation_id`,uuid,The conversation this task belongs to.
  `request_message_id`,uuid,The triggering message's id in `aidb.conversation_log`.
  `response_message_id`,uuid,"The resulting answer's id in `aidb.conversation_log`, once complete."
  `caller_role`,text,Postgres role that invoked `agent_converse`.
  `status`,`aidb.task_status`,Current lifecycle status. See  :ref:`Types<Types>`  below.
  `blocking`,boolean,Always `true` today — every task runs synchronously.
  `error`,text,"Error message, if the task failed."
  `created_at`,timestamptz,When the task started.
  `completed_at`,timestamptz,"When the task finished, if it has."

aidb.conversation_log
^^^^^^^^^^^^^^^^^^^^^

Every user prompt and agent answer, across every conversation — the same
rows ``aidb.get_conversation()`` returns, unfiltered by
``conversation_id`` . Tool calls, model requests, and other internal
activity aren’t included; query ``aidb_internal.action_log`` directly
for the full activity history.

.. csv-table::
  :header: Column,Type,Description
  :widths: 12,15,25
  :align: left
  :class: longtable

  `id`,uuid,Message id.
  `conversation_id`,uuid,The conversation this message belongs to.
  `agent_id`,uuid,The agent involved.
  `task_id`,uuid,The task this message was part of.
  `action_type`,`aidb.action_type`,`user_prompt` or `answer`.
  `payload`,jsonb,The message's raw payload (a `user_message` or `llm_response` struct).
  `created_at`,timestamptz,When the message was created.
  `completed_at`,timestamptz,When it was completed.

aidb.conversations
^^^^^^^^^^^^^^^^^^

One row per conversation, aggregated from ``aidb.conversation_log`` .

.. csv-table::
  :header: Column,Type,Description
  :widths: 12,15,25
  :align: left
  :class: longtable

  `conversation_id`,uuid,The conversation's id.
  `agent_id`,uuid,The agent involved.
  `parent_conversation_id`,uuid,Always `NULL` — conversation forking isn't implemented.
  `forked_from_message_id`,uuid,Always `NULL` — conversation forking isn't implemented.
  `status`,`aidb.task_status`,Status of the most recent task in this conversation.
  `message_count`,bigint,Number of messages in the conversation.
  `last_message_id`,uuid,Id of the most recent message.
  `created_at`,timestamptz,When the conversation started.
  `updated_at`,timestamptz,When the conversation was last updated.

--------------

Agent management functions
--------------------------

aidb.create_agent
^^^^^^^^^^^^^^^^^

Registers a new agent.

Parameters
^^^^^^^^^^

.. csv-table::
  :header: Parameter,Type,Default,Description
  :widths: 15,12,12,20
  :align: left
  :class: longtable

  `name`,TEXT,Required,Unique name for the agent.
  `instructions`,TEXT,Required,Instructions that define the agent's behavior.
  `model`,TEXT,Required,Name of the model backing the agent. See  :ref:`Choosing a model<Choosing a model>` .
  `tools`,TEXT[],NULL,Names of tools (from `aidb.tools`) the agent may call.
  `delegates`,TEXT[],NULL,Names of other agents this agent may delegate to.
  `role`,TEXT,NULL,Postgres role the agent's tool calls execute as. Caller must be a member of this role.
  `output_type`,JSONB,NULL,"Structured output schema, built with  :ref:``aidb.output_type()` <#aidboutput_type>` ."
  `input_token_budget`,INTEGER,NULL (no limit),Input token budget per `agent_converse` call.
  `output_token_budget`,INTEGER,NULL (no limit),Output token budget per call.
  `max_iterations`,INTEGER,NULL,Maximum reasoning iterations per call. A hard ceiling of 25 always applies regardless.
  `timeout`,INTEGER,NULL (300 applied at runtime),Maximum wall-clock seconds per call.
  `budget_strategy`,TEXT,`'attempt_complete'`,"One of `'ignore'`, `'error'`, `'summarize'`, `'attempt_complete'`. See  :ref:`Budgets and limits<Budgets and limits>` ."
  `preset`,TEXT,NULL,"Stored, but not currently resolved to any behavior."

Returns
^^^^^^^

``TABLE(error TEXT)`` — no rows on success; a single row with ``error``
set on failure (never raises for a validation/name-collision failure).

Example
^^^^^^^

.. code:: sql

   SELECT aidb.create_agent(
       name                 => db_helper,
       instructions         => You are a helpful assistant that answers questions about this database.,
       model                => my_gpt,
       tools                => ARRAY[run_sql_query],  -- optional; tool names from aidb.tools. Default: NULL (no tools)
       delegates            => NULL,                    -- optional; names of other agents to delegate to. Default: NULL (no delegation)
       role                 => NULL,                    -- optional; Postgres role tool calls run as. Default: NULL (run as the calling role)
       output_type          => NULL,                    -- optional; structured output schema from aidb.output_type(). Default: NULL (plain-text answer)
       input_token_budget   => NULL,                    -- optional; input token cap per agent_converse call. Default: NULL (no limit)
       output_token_budget  => NULL,                    -- optional; output token cap per agent_converse call. Default: NULL (no limit)
       max_iterations       => NULL,                    -- optional; reasoning-round cap per call. Default: NULL (a hard ceiling of 25 always applies)
       timeout              => NULL,                    -- optional; wall-clock seconds cap per call. Default: NULL (300 seconds applied at runtime)
       budget_strategy      => attempt_complete,      -- optional; behavior when a budget is exceeded. Default: attempt_complete
       preset               => NULL                     -- optional; reserved for future use, has no effect today. Default: NULL
   );

--------------

aidb.update_agent
^^^^^^^^^^^^^^^^^

Updates an existing agent. Every parameter except ``name`` is optional
and defaults to ``NULL`` , meaning “leave unchanged” — including
``budget_strategy`` , whose default here is ``NULL`` , not
``'attempt_complete'`` .

.. _parameters-1:

Parameters
^^^^^^^^^^

Same parameters as ``create_agent`` , all optional (defaulting to
``NULL`` ) except ``name`` .

.. _returns-1:

Returns
^^^^^^^

``TABLE(error TEXT)`` — no rows on success; a single row with ``error``
set on failure (agent not found, invalid field value).

.. _example-1:

Example
^^^^^^^

.. code:: sql

   SELECT aidb.update_agent(db_helper, model => my_new_gpt, max_iterations => 15);

--------------

aidb.delete_agent
^^^^^^^^^^^^^^^^^

Deletes an agent by name.

.. _parameters-2:

Parameters
^^^^^^^^^^

.. csv-table::
  :header: Parameter,Type,Default,Description
  :widths: 15,12,12,20
  :align: left
  :class: longtable

  `name`,TEXT,Required,Name of the agent to delete.
  `force`,BOOLEAN,NULL (false),"If `true`, also deletes the agent's internal task/action-queue records so deletion can proceed even if it has conversation history. The conversation transcript itself (`aidb.conversation_log`) is preserved either way."

.. _returns-2:

Returns
^^^^^^^

``TABLE(error TEXT)`` — no rows on success; a single row with ``error``
set on failure, including when the agent has conversation history and
``force`` wasn’t passed.

.. _example-2:

Example
^^^^^^^

.. code:: sql

   SELECT aidb.delete_agent(db_helper, force => true);

--------------

Conversation functions
----------------------

aidb.agent_converse
^^^^^^^^^^^^^^^^^^^

Runs an agent’s reasoning loop against a prompt and returns its answer.

.. _parameters-3:

Parameters
^^^^^^^^^^

.. csv-table::
  :header: Parameter,Type,Default,Description
  :widths: 15,12,12,20
  :align: left
  :class: longtable

  `agent_name`,TEXT,Required,Name of the agent to converse with.
  `prompt`,TEXT,Required,The prompt to send.
  `conversation_id`,TEXT,NULL,Continue an existing conversation. Omit to start a new one (an id is generated automatically).
  `read_only`,BOOLEAN,NULL,Force  :ref:`Read-only mode<Read-only mode>`  on or off. Auto-enabled on a read replica when omitted.
  `output_type`,JSONB,NULL,Overrides the agent's configured  :ref:`Structured output<Structured output>`  schema for this call only.
  `debug`,BOOLEAN,NULL,"If `true`, also emit every action as a `NOTICE`. See  :ref:`Debug mode<Debug mode>` ."

.. _returns-3:

Returns
^^^^^^^

``TABLE(message TEXT, conversation_id TEXT, error TEXT)`` — one row.
Never raises for an agent-logic failure; ``error`` is populated instead,
and ``message`` /``conversation_id`` are ``NULL`` . ``conversation_id``
is also ``NULL`` for any read-only run, since nothing is persisted to
attach an id to.

.. _example-3:

Example
^^^^^^^

.. code:: sql

   SELECT * FROM aidb.agent_converse(
       agent_name      => db_helper,
       prompt          => How many rows are in the orders table?,
       conversation_id => NULL,  -- optional; continue an existing conversation by id. Default: NULL (starts a new conversation)
       read_only       => NULL,  -- optional; force read-only mode on/off. Default: NULL (auto: on for a read replica, off otherwise)
       output_type     => NULL,  -- optional; override the agents structured output schema for this call. Default: NULL (use the agents own configuration)
       debug           => NULL   -- optional; also emit every action as a NOTICE. Default: NULL (false)
   );

--------------

aidb.start_agent_session
^^^^^^^^^^^^^^^^^^^^^^^^

Mints a fresh conversation id for a named agent, ahead of the first
``agent_converse`` call that will use it.

.. _parameters-4:

Parameters
^^^^^^^^^^

.. csv-table::
  :header: Parameter,Type,Description
  :widths: 12,15,25
  :align: left
  :class: longtable

  `agent_name`,TEXT,Name of the agent to converse with.

.. _returns-4:

Returns
^^^^^^^

``TABLE(conversation_id TEXT)`` . Unlike ``agent_converse`` , this
function **raises** (rather than returning an ``error`` column) if
``agent_name`` is empty or unknown.

.. _example-4:

Example
^^^^^^^

.. code:: sql

   SELECT * FROM aidb.start_agent_session(db_helper);

--------------

aidb.get_conversation
^^^^^^^^^^^^^^^^^^^^^

Retrieves a conversation’s messages — every user prompt and final
answer, in chronological order. Excludes tool calls and other internal
activity; see ``aidb_internal.action_log`` for the full activity
history.

.. _parameters-5:

Parameters
^^^^^^^^^^

.. csv-table::
  :header: Parameter,Type,Description
  :widths: 12,15,25
  :align: left
  :class: longtable

  `conversation_id`,TEXT,The conversation's id.

.. _returns-5:

Returns
^^^^^^^

``TABLE(message_id TEXT, task_id TEXT, action_type TEXT, role TEXT, sender_id TEXT, contents TEXT)``
— one row per message. ``role`` is ``"user"`` or ``"agent"`` ;
``sender_id`` is the specific sender (the prompt’s own ``user`` field,
or the agent’s id). **Raises** (rather than returning an ``error``
column) if ``conversation_id`` is empty.

.. _example-5:

Example
^^^^^^^

.. code:: sql

   SELECT * FROM aidb.get_conversation(8f14e45f-ceea-467e-9575-a3d1a2c1a123);

--------------

aidb.get_message
^^^^^^^^^^^^^^^^

Retrieves one message’s plain-text contents by id.

.. _parameters-6:

Parameters
^^^^^^^^^^

.. csv-table::
  :header: Parameter,Type,Description
  :widths: 12,15,25
  :align: left
  :class: longtable

  `message_id`,TEXT,The message's id.

.. _returns-6:

Returns
^^^^^^^

``TABLE(message TEXT, error TEXT)`` — one row. ``error`` (not
``message`` ) is populated when no such message exists; doesn’t raise.

.. _example-6:

Example
^^^^^^^

.. code:: sql

   SELECT * FROM aidb.get_message(3fa85f64-5717-4562-b3fc-2c963f66afa6);

--------------

Structured output helpers
-------------------------

aidb.output_field
^^^^^^^^^^^^^^^^^

Builds one field of an agent’s structured output schema.

.. _parameters-7:

Parameters
^^^^^^^^^^

.. csv-table::
  :header: Parameter,Type,Default,Description
  :widths: 15,12,12,20
  :align: left
  :class: longtable

  `name`,TEXT,Required,The field's name.
  `field_type`,TEXT,Required,"The field's type (for example, `'TEXT'`, `'FLOAT'`, `'BOOLEAN'`)."
  `description`,TEXT,NULL,Description shown to the model.

.. _returns-7:

Returns
^^^^^^^

``JSONB`` — pass one or more of these to ``aidb.output_type()`` .

--------------

aidb.output_type
^^^^^^^^^^^^^^^^

Builds a complete structured output schema from one or more fields.

.. _parameters-8:

Parameters
^^^^^^^^^^

.. csv-table::
  :header: Parameter,Type,Description
  :widths: 12,15,25
  :align: left
  :class: longtable

  `fields`,VARIADIC JSONB[],One or more `aidb.output_field()` results.

.. _returns-8:

Returns
^^^^^^^

``JSONB`` — pass to ``create_agent`` /``update_agent`` ’s
``output_type`` parameter, or ``agent_converse`` ’s.

.. _example-7:

Example
^^^^^^^

.. code:: sql

   SELECT aidb.create_agent(
       name         => sentiment_tagger,
       instructions => Classify the sentiment of the given text.,
       model        => my_gpt,
       output_type  => aidb.output_type(
           aidb.output_field(sentiment, TEXT, One of: positive, negative, neutral),
           aidb.output_field(confidence, FLOAT)
       )
   );

--------------

Types
-----

aidb.budget_strategy
^^^^^^^^^^^^^^^^^^^^

.. code:: sql

   CREATE TYPE aidb.budget_strategy AS ENUM (
       ignore,
       error,
       summarize,
       attempt_complete
   );

See :ref:`Budgets and limits <Budgets and limits>`  for what each value does.

aidb.task_status
^^^^^^^^^^^^^^^^

.. code:: sql

   CREATE TYPE aidb.task_status AS ENUM (
       PENDING,
       IN_PROGRESS,
       RECOVERY,
       AWAIT_APPROVAL,
       DENIED,
       ERROR,
       TIMEOUT,
       CANCELED,
       SUCCESS,
       EVALUATING,
       COMPLETE
   );

Surfaced through ``aidb.agent_tasks.status`` and
``aidb.conversations.status`` . Since every task today runs
synchronously to completion within one ``agent_converse`` call, a task’s
terminal status is normally ``SUCCESS`` or ``ERROR`` ; the remaining
values are reserved for asynchronous/approval workflows that aren’t
implemented yet.
