Skip to main content

dj-pydantic-agents

Agent turns, streaming and approvals for Django. Not the same package as django-pydantic-ai, which stores memory and conversations.

Status

Version 0.1 is complete. Vintage Eye is the first project that uses it. It has no production use yet.

Needs

  • Python 3.14 or later
  • Django 6.0 or later
  • PostgreSQL
  • Redis, for the Redis Stream transport
  • pydantic-ai-slim==2.68.* and pydantic-ai-harness==0.68.*

Install

Install the package from PyPI. Select the extras that the project uses: celery, codex and datastar.

uv add "dj-pydantic-agents[celery,codex,datastar]==0.7.0"

Usage limits

USAGE_LIMITS holds the keyword arguments of pydantic_ai.usage.UsageLimits for one run of a turn. A run that goes over a limit fails with the code usage_limit. The default is None, with no limit.

DJ_PYDANTIC_AGENTS = {
    ...,
    "USAGE_LIMITS": {"request_limit": 60},
}

A resume after approvals is a new run, so it gets the full limits again. The Harness SubAgents capability adds the usage of each child to the run by default. Then the limits also cover the children. The check dj_pydantic_agents.E007 fails when UsageLimits does not accept the value.

Files in a message

The package sends the files of a user message to the model, as BinaryContent. The project stores the files. It also does the upload, the type checks and the cleanup. The package keeps only a reference of each file in the history: its ID, its name and its type.

The chat takes no files by default. To take files, give a class with the PromptFiles contract of dj_pydantic_agents.extensions:

DJ_PYDANTIC_AGENTS = {
    ...,
    "PROMPT_FILES": "myproject.agents.prompt_files.AgentPromptFiles",
    "FILE_HISTORY_TURNS": 2,  # The latest turns, with the current turn.
}

The class has five methods:

  • pending(conversation_id, user_id): the files that wait for the next message. The page shows them in the message form.
  • claim(conversation_id, user_id, turn_id, file_ids): bind the files to the new turn. start_turn() calls it in its transaction, after it adds the turn. Raise FilesRefused to stop the send. The rollback also removes the turn, and the form shows the text of the error.
  • describe(file_ids): the size and the URL of each file of the transcript. Leave out an unknown ID. The page then shows the name from the history.
  • load(turn_ids): the bytes of the files of these turns, as PromptFile items. A worker calls it before each run.
  • forget(conversation_id): delete the files of a deleted conversation. delete_conversation() calls it after the delete. The package logs an error of it and does not raise it.

The send view reads a form field file for each file ID. The default message_form.html has no file input. A project override adds the input and a hidden file field for each pending file.

The stored history holds no file bytes. Before each run, the worker loads the files of the latest FILE_HISTORY_TURNS turns. An older file stays out of the request, and its label tells the model that. The check dj_pydantic_agents.E008 fails when FILE_HISTORY_TURNS is not an integer of 1 or more.

Celery

Install the extra: dj-pydantic-agents[celery]. Then add the app and the task runner:

INSTALLED_APPS = [
    ...,
    "dj_pydantic_agents",
    "dj_pydantic_agents.contrib.celery",
]

DJ_PYDANTIC_AGENTS = {
    ...,
    "TASK_RUNNER": "dj_pydantic_agents.contrib.celery.runner.CeleryTaskRunner",
    "CELERY_QUEUE": "agents",  # Optional. The default is the default Celery queue.
}

The worker finds the turn task through app.autodiscover_tasks(). Without the app in INSTALLED_APPS, the worker does not know the task, and the check dj_pydantic_agents.E006 fails.

The task uses the Celery time limits of the project. A turn can take more time than other tasks. To set the limits for the turn task only, use CELERY_TASK_ANNOTATIONS:

CELERY_TASK_ANNOTATIONS = {
    "dj_pydantic_agents.run_turn": {"soft_time_limit": 600, "time_limit": 660},
}

Datastar

Install the extra: dj-pydantic-agents[datastar]. The app has three views: send a message, decide an approval, and stream a turn. Each view returns Datastar patches. The project writes each full page.

INSTALLED_APPS = [
    ...,
    "dj_pydantic_agents",
    "dj_pydantic_agents.contrib.datastar",
]

DJ_PYDANTIC_AGENTS = {
    ...,
    # A queued or running turn with no status change for this time lost its
    # worker. The stream view then fails it with worker_lost. Make it longer
    # than the hard time limit of the turn task.
    "STALE_TURN_SECONDS": 1800,  # The default.
}

Include the URLs. The namespace is dj_pydantic_agents:

urlpatterns = [
    ...,
    path("agents/", include("dj_pydantic_agents.contrib.datastar.urls")),
]

The stream view streams. Serve the project with an ASGI server, for example uvicorn. runserver cannot stream.

The text of a reply

The stream view shows the text of a reply in small steps, about one word each 45 milliseconds. The model sends its text in uneven parts, so the view keeps the text in a buffer. When the buffer grows, the steps grow too, so the text stays close to the model.

Each top-level element of the reply text gets the ID djpa-reply-<turn ID>-text-<number>. A patch morphs only the block that changed, and a new block goes at the end. While the text streams, the view closes an open code fence, inline code span or bold text. It holds back a table until its delimiter row comes.

A new stream, for example after a reload, shows the earlier text in one patch.

The morph keeps each block that stays on the page. So a CSS animation on .djpa-reply__text > * plays only for a new block.

Keep CONN_MAX_AGE at 0, the default, in DATABASES. The Django documentation says to disable persistent connections in async mode. Use the PostgreSQL pool of Django if you need a pool. The views free their database connection before the stream waits for events.

The project pages

The project writes the chat page and the "New conversation" view. Each view calls one service:

from dj_pydantic_agents.composition import build_conversation_command_service
from dj_pydantic_agents.composition import build_conversation_query_service
from dj_pydantic_agents.dtos.conversation_queries import GetConversationPageQueryDTO
from dj_pydantic_agents.dtos.turn_commands import CreateConversationCommandDTO


@staff_member_required
@require_POST
def new_conversation(request):
    created = build_conversation_command_service().create_conversation(
        command=CreateConversationCommandDTO(owner_id=request.user.pk, agent_name="assistant"),
    )
    return redirect("dashboard:agent_chat", conversation_id=created.conversation_id)


@staff_member_required
def agent_chat(request, conversation_id):
    page = build_conversation_query_service().get_conversation_page(
        query=GetConversationPageQueryDTO(conversation_id=conversation_id, user_id=request.user.pk),
    )
    return render(request, "dashboard/agent_chat.html", {"page": page})

list_conversations() of the query service gives the conversations of a user with an agent, newest first.

The command service also renames and deletes a conversation:

  • rename_conversation(command=RenameConversationCommandDTO(...)) sets the title. The title loses its outer spaces and has 1 to 200 characters. A rename can occur during a turn. The conversation keeps its place in the list.
  • delete_conversation(command=DeleteConversationCommandDTO(...)) deletes the conversation, its turns and its approvals. A conversation with an active turn raises TurnInProgress.

Both raise ConversationNotFound when the conversation does not exist or another user owns it.

The page template loads Datastar 1 and includes the chat:

{% include "dj_pydantic_agents/chat.html" %}

The template needs page and csrf_token in the context. render() adds csrf_token. Each package form sends the token in the X-CSRFToken header, so the package does not need django-datastar.

A Cotton project can wrap the include in a component, for example templates/cotton/agent_chat.html:

{% include "dj_pydantic_agents/chat.html" %}

Then the page uses <c-agent-chat :page="page" />.

Templates and class names

The templates are plain Django templates in dj_pydantic_agents/: chat.html, transcript_line.html, reply.html, tool_steps.html, tool_label.html, run_end.html, approval_card.html, message_form.html and csrf_option.html. tool_label.html holds the words for a tool, for example "Searching the web", "Searched the web" and "Used ". It also has words for delegate_task, the tool of the Harness SubAgents capability: "Delegating a task", "Delegated a task" and "Result of a task". To change one, put a template at the same path in the templates/ folder of the project. An override of approval_card.html must keep the partial actions.

An override of message_form.html must keep the partial error and its ID djpa-message-form-error. Each Datastar POST of the templates sends the CSRF header of csrf_option.html. A project with a CSRF bridge for Datastar requests can put an empty file in its place.

The package has no CSS. Style these classes:

  • djpa-chat, djpa-chat__scroll (the scroll pane), djpa-transcript
  • djpa-line with djpa-line--user, djpa-line--assistant, djpa-line--tool-call, djpa-line--tool-result or djpa-line--error, and djpa-line__summary, djpa-line__data. A tool line is a closed <details> element.
  • djpa-reply, djpa-reply__steps, djpa-step (a step line while the reply streams), djpa-reply__text
  • djpa-approval, djpa-approval__tool, djpa-approval__args, djpa-approval__actions, djpa-approval__form, djpa-approval__approve, djpa-approval__deny, djpa-approval__decision
  • djpa-message-form, djpa-message-form__input, djpa-message-form__send, djpa-message-form__error
  • djpa-files, djpa-files__item (the files of a user line, before the line)

A chat with a fixed size and a scroll pane needs four rules. With column-reverse, the browser keeps the view at the newest line, with no JavaScript:

.djpa-chat { display: flex; flex-direction: column; height: 100%; min-height: 0; }
.djpa-chat__scroll { flex: 1; min-height: 0; display: flex; flex-direction: column-reverse; overflow-y: auto; }
.djpa-message-form { flex: none; display: flex; }
.djpa-message-form__input { flex: 1; min-width: 0; }

The parent of djpa-chat must have a fixed height, for example 100dvh minus the header. tests/demo/templates/demo/base.html has a full responsive example.

The demo

tests/demo/ is a small project for a test in a browser. It uses the Redis transport, a scripted model and a thread task runner:

docker compose up -d
uv run django-admin migrate --settings=tests.demo.settings --pythonpath=.
uv run --with uvicorn uvicorn tests.demo.asgi:application --port 8001

Then open http://127.0.0.1:8001/.

Codex: the ChatGPT plan of each user

Install the extra: dj-pydantic-agents[codex]. Each user connects their own ChatGPT plan. The turns of that user then use the openai-codex provider of Pydantic AI with the tokens of that user.

INSTALLED_APPS = [
    ...,
    "dj_pydantic_agents",
    "dj_pydantic_agents.contrib.codex",
]

DJ_PYDANTIC_AGENTS = {
    ...,
    "MODEL_FACTORY": "dj_pydantic_agents.contrib.codex.model_factory.CodexModelFactory",
    "MODEL_NAMES": {"chat": "gpt-6.1-sol", "summary": "gpt-6-luna"},
    # Fernet keys. The first key encrypts, each key decrypts. Keep them out of the code.
    "CODEX_TOKEN_KEYS": env.list("CODEX_TOKEN_KEYS"),
}

Make a key with this command:

python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"

To change the key, put the new key first and keep the old key second. A login or a token refresh then encrypts with the new key. The check dj_pydantic_agents.E007 finds a missing or bad key.

The encrypted value also holds the user ID. A copy of the value to the row of another user does not decrypt.

The login pages

The login uses a copy and paste of an address. After the sign-in, the browser opens http://localhost:1455/auth/callback?code=.... That page does not load on a server. The user copies its address into a form. A login must complete in 10 minutes.

The project writes the two pages. Each view calls one service:

from dj_pydantic_agents.contrib.codex.composition import build_plan_login_service
from dj_pydantic_agents.contrib.codex.dtos import CompletePlanLoginCommandDTO
from dj_pydantic_agents.contrib.codex.dtos import StartPlanLoginCommandDTO
from dj_pydantic_agents.contrib.codex.errors import PlanLoginFailed


@staff_member_required
def plan_login(request, error=""):
    started = build_plan_login_service().start_login(
        command=StartPlanLoginCommandDTO(user_id=request.user.pk),
    )
    return render(
        request,
        "dashboard/plan_login.html",
        {
            "authorization_url": started.authorization_url,
            "form_action": reverse("dashboard:plan_login_complete"),
            "error": error,
        },
    )


@staff_member_required
@require_POST
def plan_login_complete(request):
    try:
        build_plan_login_service().complete_login(
            command=CompletePlanLoginCommandDTO(
                user_id=request.user.pk,
                pasted_url=request.POST.get("pasted_url", ""),
            ),
        )
    except PlanLoginFailed as error:
        return plan_login(request, error=str(error))
    return redirect("dashboard:agent_chat_list")

get_plan_status() tells if the user saved a plan, and gives the account ID. It reads only the saved row. It does not decrypt the tokens and makes no request, so a token that OpenAI revoked still shows as connected. The next turn then fails with plan_not_connected.

from dj_pydantic_agents.contrib.codex.dtos import GetPlanStatusQueryDTO

status = build_plan_login_service().get_plan_status(
    query=GetPlanStatusQueryDTO(user_id=request.user.pk),
)
# status.connected: bool, status.account_id: str | None

The page template includes the form:

{% include "dj_pydantic_agents/codex/login_form.html" %}

The form classes are djpa-codex-login, with __steps, __link, __error, __form, __input and __submit.

The tokens in the workers

  • A turn of a user with no login fails with the code plan_not_connected.
  • A refresh token works one time. Before a refresh, a worker takes a lease of 30 seconds on the row of the user. Another worker waits, then uses the new tokens.
  • The provider does not use background mode, because the backend cannot resume a background response.
  • The model names in MODEL_NAMES go to the backend unchanged. The backend accepts or refuses them.

Development

uv sync --all-extras
docker compose up -d
uv run pytest

PostgreSQL runs in Docker on host port 5433, and Redis on host port 6380.

Metadata

Release files for dj-pydantic-agents 0.7.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for dj-pydantic-agents 0.7.0
File Size Uploaded Provenance Actions
dj_pydantic_agents-0.7.0.tar.gz 63.2 kB With provenance Details for dj_pydantic_agents-0.7.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for dj-pydantic-agents 0.7.0
File Interpreter ABI Platform Actions
dj_pydantic_agents-0.7.0-py3-none-any.whl Python 3 none any Details for dj_pydantic_agents-0.7.0-py3-none-any.whl

Total release size: 155.3 kB

Release files / dj_pydantic_agents-0.7.0.tar.gz

Download URL dj_pydantic_agents-0.7.0.tar.gz
Size 63.2 kB
Tags Source
SHA-256 checksum
How to use checksums
098af638f930ca11170cb65769ec225f934d6db6b94289a5bd595e38f1cf2ca4
BLAKE2b-256 checksum
How to use checksums
676c40a76264c539c52af90e6c1c77071defbfb8e9d9b90e29b241e75d8a51aa
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 18, 2026.

Transparency log

Release files / dj_pydantic_agents-0.7.0-py3-none-any.whl

Download URL dj_pydantic_agents-0.7.0-py3-none-any.whl
Size 92.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
813cb39a2cdaf6346fae4f1a606590ca9fc4291c80a4dc4a0487603205ed9ca4
BLAKE2b-256 checksum
How to use checksums
7712607bc231b4e0f328e66a13bb1053f5ec6496f68defbe8346d30c643de3b9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 18, 2026.

Transparency log

Security for dj-pydantic-agents 0.7.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for dj_pydantic_agents-0.7.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 18, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page