AgentGraft

Reference

The SDK

Four decorators, four config functions, a client, one settings dict and one CLI command. The full Python surface, in one page.

20 min read

The SDK is one Python package, agentgraft. Its config DSL is four decorators (@ag.tool, @ag.agent, @ag.user_loader, @ag.on_tool_call) and four functions (ag.graft, ag.policy, ag.reference, ag.ref). Around it sit a settings dict (the host app config), one Django management command (the sync), the webhook handler, and ag.Client for calling AgentGraft from your server.

#Installation

bash
pip install "agentgraft[django]"   # Django app: management command, webhook view, template tag
pip install agentgraft             # core only: registry, decorators, schema โ€” no Django required

Python 3.14+ is required. The core package has no runtime dependencies beyond the standard library. Django is an optional extra โ€” install agentgraft[django] for the full Django integration, or agentgraft alone when using the core SDK from another framework (FastAPI, Flask, raw WSGI).

#Settings

Add "agentgraft.django" to INSTALLED_APPS. At startup it imports AGENTGRAFT["config_module"] (default "agentgraft_config", a top-level agentgraft_config.py), which runs your decorators. Each chat experience is a profile under AGENTGRAFT["profiles"]; a single-profile app uses "default".

python
# settings.py
INSTALLED_APPS = [
    # ...
    "agentgraft.django",
]

AGENTGRAFT = {
    "config_module": "myapp.agentgraft_config",  # default: "agentgraft_config"
    "profiles": {
        "default": {
            "api_base":       "https://agentgraft.com",
            "api_key":        os.environ["AGENTGRAFT_API_KEY"],
            "public_key":     os.environ["AGENTGRAFT_PUBLIC_KEY"],
            "graft_id":       os.environ["AGENTGRAFT_GRAFT_ID"],
            "webhook_secret": os.environ["AGENTGRAFT_WEBHOOK_SECRET"],
            "webhook_url":    "https://myapp.com/agentgraft/webhook/",  # optional
        },
    },
}
  • api_base โ€” the AgentGraft origin. Used by the sync, the widget tag and Client.
  • api_key โ€” secret. Needed by the sync and by the Client calls only your server may make.
  • public_key โ€” browser-safe. Written into the widget tag, and sent by Client chat calls.
  • graft_id โ€” the graft the sync pushes to.
  • webhook_secret โ€” verifies the tool calls AgentGraft sends you, and signs your visitors' ids.
  • webhook_url (optional) โ€” where AgentGraft sends tool calls. Wins over ag.graft(webhook_url=...) when both are set.
  • detailed_errors (optional, off) โ€” send the text of an exception your code raised to the model, instead of a generic message (see The webhook view).

Read api_key and webhook_secret from environment variables, never from a checked-in settings file. Client.from_profile reads the same four connection keys.

#@ag.user_loader

Resolves an external user id back to your domain user object. Called on every tool call, before the tool and its hooks run; whatever it returns becomes the first positional argument to every tool function in the same profile. The template tag sends signed-in users as user:{pk}, so strip the prefix. Raising fails the call with a 403 and a generic message; raise ag.WebhookError(status, message) to send your own. Like tools, it must be a plain def: async def is refused at import.

python
@ag.user_loader
def load_user(external_id: str) -> User:
    return User.objects.get(pk=external_id.removeprefix("user:"))

If your widget is rendered for anonymous visitors too, declare the loader with an is_anonymous keyword and the SDK will pass it on every call. It's True whenever the external id is in the session: namespace: the id AgentGraft derives for a logged-out visitor from the one the widget picked for their browser. It is not a Django session key, so don't look a session up with it. Loaders that don't declare the keyword still work โ€” the SDK introspects the signature and only forwards what the function expects.

python
@ag.user_loader(profile="public")
def load_guest(external_id: str, *, is_anonymous: bool = True) -> dict:
    return {"visitor_id": external_id.removeprefix("session:")}

#@ag.tool

Marks a function as a tool the LLM can call. The first argument is the resolved user object โ€” it's not visible to the LLM, the SDK injects it. Every other argument's type hint becomes a JSON schema field; the docstring becomes the tool description.

python
@ag.tool
def search_assets(user: User, query: str, limit: int = 10) -> list[dict]:
    """Search the user's assets by name or ticker.

    Use this for stock lookups, crypto symbols, anything in the
    portfolio. Returns up to ``limit`` matches with ticker, name,
    and current quote.
    """
    matches = Asset.objects.filter(owner=user, name__icontains=query)[:limit]
    return [{"ticker": a.ticker, "name": a.name, "price": str(a.price)} for a in matches]

Return values must be plain JSON: dicts, lists, strings, numbers, booleans and None. Convert Decimal, datetime and model instances yourself; anything else is a 500.

Every parameter after user needs a type hint; one without fails at import with a ValueError. The supported hints are str, int, float, bool (and their subclasses), Decimal, date, datetime, time, UUID, list[T] and other sequences, dict and other mappings, Optional[T], unions, Literal[...], Enum subclasses, Any, and Pydantic (v2) models or lists of them. A default makes a parameter optional in the schema, and so does Optional without one: it then arrives as None when the model leaves it out. Only Pydantic models are converted: every other argument reaches your function as the JSON the model sent, so a date is its ISO 8601 string. Anything more exotic (dataclasses, bytes, timedelta) gets an untyped field and a UserWarning: unwrap it to primitives, or annotate it Any on purpose. *args and **kwargs stay out of the schema.

The docstring is the tool's description, or pass @ag.tool(description="..."). Tools are plain def functions: the webhook calls them synchronously, so async def is refused at import. Tool names only have to be unique within their profile.

A Pydantic-typed parameter is sent to the LLM as the model's JSON schema, with references inlined, and the argument reaches your function as a validated instance (None for an Optional one sent as null). One that doesn't validate is a 400 saying where and what is wrong, so the model can correct its call. Use it for structured input that a few primitives can't express:

python
from pydantic import BaseModel, Field


class LineItem(BaseModel):
    sku: str = Field(description="Product SKU, as returned by search_products.")
    quantity: int = Field(default=1, ge=1, le=99)


@ag.tool
def create_order(user: User, items: list[LineItem], note: str = "") -> dict:
    """Place an order for the user's items."""
    order = Order.objects.create(owner=user, note=note)
    for item in items:  # validated LineItem instances
        order.lines.create(sku=item.sku, quantity=item.quantity)
    return {"id": order.pk}

AgentGraft retries a call once if it can't reach your webhook (connection refused or timed out, or the request cut off) or your webhook answers 502, 503 or 504. It waits up to 120 seconds for an answer, and a call that times out while your tool runs is not retried, since the tool may still be working. Tools that write should call ag.current_request_id() and use it as an idempotency key; the id is the same on the retry. See the Wire protocol page for an example.

#Parameter descriptions

The LLM fills in tool arguments using the parameter name, its type, and โ€” if provided โ€” a natural-language description. Descriptions flow directly into the JSON schema the LLM receives and are one of the highest-leverage ways to improve tool call accuracy. There are two ways to add them; both produce the same result.

Write a standard Args: block in the docstring. The SDK extracts it automatically when the decorator runs โ€” no extra imports, no annotation changes needed. The Args: section, and everything after it (Returns:, Raises:, โ€ฆ), is left out of the tool-level description before it reaches the LLM, so the model sees a clean summary in the tool description and targeted guidance in each parameter's schema field.

python
@ag.tool
def get_order(user, order_id: str, include_line_items: bool = False) -> dict:
    """Fetch a single order by ID.

    Args:
        order_id: UUID of the order to fetch, as returned by list_orders.
        include_line_items: Pass True to include individual line items in
            the response. Defaults to False.
    """
    return Order.objects.get(owner=user, pk=order_id).to_dict(include_line_items)

@ag.tool
def list_orders(
    user,
    status: Literal["pending", "fulfilled", "cancelled"] = "pending",
    limit: int = 20,
) -> list[dict]:
    """List the user's orders, newest first.

    Args:
        status: Filter orders by fulfilment status.
        limit: Maximum number of orders to return.
    """
    return list(Order.objects.filter(owner=user, status=status)[:limit].values())

Accepted headers: Args:, Arguments:, Parameters:, Params: (case-insensitive). Multi-line descriptions (indented continuation lines) are joined with a space. Type annotations in name (type): form are ignored โ€” the SDK already has the type from the signature.

#Option 2 โ€” ag.Param explicit override

Use ag.Param when you need to override a single parameter independently without rewriting the docstring, or when you want to attach examples that the docstring format can't express. ag.Param always wins over the docstring Args: entry for the same parameter โ€” other parameters in the same function still fall through to the docstring.

python
from typing import Annotated, Literal
import agentgraft as ag

@ag.tool
def list_orders(
    user,
    status: Annotated[
        Literal["pending", "fulfilled", "cancelled"],
        ag.Param("Filter orders by fulfilment status"),
    ] = "pending",
    limit: Annotated[int, ag.Param("Maximum number of orders to return", examples=[10, 50])] = 20,
) -> list[dict]:
    """List the user's orders, newest first."""
    return list(Order.objects.filter(owner=user, status=status)[:limit].values())

The examples list (optional) is merged into the parameter's JSON schema entry. Literal types automatically generate an enum constraint โ€” combine them with ag.Param to tell the model both what values are valid and what they mean.

#@ag.agent

Declares an agent: a named persona with instructions, a list of tools, and optional handoff targets. The function body isn't executed; only its docstring matters (it becomes the agent's system prompt fragment) and the decorator arguments. Naming a function def helper(): and decorating it produces an agent named helper.

python
@ag.agent(entry=True, tools=[list_datasets, get_dataset])
def router():
    """You route incoming messages. For greetings or small talk,
    answer directly in one line. For data questions, hand off to
    ``data_helper`` immediately."""


@ag.agent(tools=[list_datasets, get_dataset, recent_queries])
def data_helper():
    """You help users explore their datasets. Always call a tool
    before answering; never invent values."""


@ag.agent(handoffs=["router"])
def fallback():
    """You handle anything off-topic. Politely redirect back to
    what the app actually does, then hand off to router."""

At most one agent per graft may be entry=True, and the widget needs one: every conversation not started on a named agent (see Running agents from your server) begins there. tools, handoffs and sub_agents take the decorated functions or their names as strings, so you can name an agent defined further down the file; sync checks every name and rejects unknown ones, and an agent listing itself as a sub-agent. An agent without a docstring fails at import with a ValueError.

Use sub_agents=[...] when you want one agent to delegate a task to another and receive a result back, rather than transferring the conversation. The sub-agent runs its own tool loop internally and returns a string; the calling agent stays in control and can use that result in its next step. This is the orchestrator pattern โ€” contrast it with handoffs=, which hands the conversation over entirely.

python
@ag.agent(sub_agents=["researcher"], entry=True)
def advisor():
    """You advise users on their portfolio. When you need current market
    data or detailed research on a symbol, delegate to 'researcher' and
    use its result in your answer. Compose the final response yourself.
    """


@ag.agent(tools=[search_news, get_price_history])
def researcher():
    """You gather factual data. Call the tools you have, then return
    a concise factual summary for the advisor to use.
    """

An optional model argument pins the agent to a specific Cailos model codename. The default auto hands routing to Cailos; auto:speed and auto:cost are Cailos's speed- and cost-biased routes. Concrete ids like claude-opus-4-7, claude-sonnet-4-6, claude-haiku-4-5, or gpt-5 also work โ€” whatever string you pass is sent to Cailos verbatim, so the source of truth for valid codenames is Cailos's model list. Invalid codenames surface as Cailos errors at request time; AgentGraft itself does no validation.

#Private chat

Mark one agent private=True and the widget gets an incognito chat: a ghost button in the header opens a conversation with that agent that AgentGraft does not save. No conversation, no messages, no long-term memory, no titles or recaps. The widget holds the transcript in the page and sends the recent turns with each message, so leaving the chat or reloading the page discards it.

python
@ag.agent(private=True, tools=[search_docs])
def incognito():
    """You answer questions the visitor would rather not keep.
    Use search_docs for anything about the product."""
  • At most one private agent per graft, and it cannot be the entry point.
  • It cannot declare handoffs or sub_agents (nor be the entry point or unattended): the decorator raises ValueError at import. No other agent can hand off to it or call it, and sync rejects a second private agent.
  • It sees the graft prompt (identity, voice, scope, policies, references), the visitor's display name and the current date. It gets no memory tools and no stored facts, even when memory_enabled is on. Its own tools work as usual.
  • Each message carries the most recent turns that fit in half the graft's context_window_tokens, up to 40 messages. Older turns drop out of the agent's view.
  • Its spend counts toward visitor_quota_usd like any other turn.

#Agents your server runs

Mark an agent unattended=True when no person reads its replies as they come: a bot or a scheduled job your server runs through Client. Its replies get no suggested follow-ups and no auto-title, and its conversations no Reflector questions. Those are all written for a reader, and each costs a model call. Its long-term memory works as usual. It cannot be the private agent, which a person reads.

python
@ag.agent(tools=[search_notes, file_clipping], unattended=True)
def researcher():
    """You research a topic for the user who hired you and file what you find."""

#An agent's own identity

The graft's identity opens every agent's prompt. Give an agent an identity of its own when it isn't the graft's main assistant, such as a bot with a name of its own: it takes the place of the graft's in that agent's prompt. The graft's other layers (product context, voice, scope, policies, references) still apply. Blank keeps the graft's.

python
@ag.agent(tools=[search_notes], unattended=True, identity="You are Scout, a research bot.")
def scout():
    """You research a topic for the user who hired you and file what you find."""

#Agents without memory

Long-term memory belongs to the visitor, so every agent of the graft shares it. Set memory=False on an agent whose replies other people read, such as a bot in a shared room, so nothing the visitor told another agent can surface there. The agent gets no memory tools and no memories in its prompt, and its own turns feed no memory: a turn that starts on it reads no mood and schedules no Dreamer pass, and a conversation it holds is not dreamed. Its conversations and messages are still saved, and the visitor's agents with memory on can search those messages as they search any, and remember what they find. The graft's other agents keep their memory. It can't hand off to or call an agent with memory on, nor be handed off to or called by one: agentgraft_sync refuses the link, as memory would pass across it. Sync only once the server knows the setting: an older one keeps the agent's memory on.

python
@ag.agent(tools=[post_reply], identity="You are Scout, a research bot.", memory=False)
def scout_in_rooms():
    """You answer in a room the user shares with other people."""

#ag.graft(...)

Sets the graft-level prompt context. Every agent's system prompt is composed at runtime by stacking these blocks before the agent's own instructions, so the same identity, voice, scope, and policies apply across every conversation.

python
ag.graft(
    name="Acme",
    identity="You are Acme's in-app assistant.",
    product_context=(
        "Acme is a B2B analytics platform. Users own datasets,"
        " run queries, and share dashboards with their teams."
    ),
    voice="Be concise. Use British English. Cite the dataset name when quoting figures.",
    scope=(
        "IN SCOPE: dataset queries, dashboard navigation, query syntax help.\n"
        "OUT OF SCOPE: financial advice, anything off-platform."
    ),
    policies=[
        ag.policy("agentgraft/no-hallucination"),
        ag.policy("agentgraft/cite-sources"),
        "Never reveal API keys or any value beginning with sk_.",
    ],
    greeting="Ask me about your data.",
    example_prompts=["What datasets do I have?", "Show me yesterday's queries"],
)

Every field is optional, but your config is the source of truth: a prompt field, greeting or example_prompts you leave out is cleared on the next sync, as is anything edited in the dashboard, and tools and agents no longer declared are removed. Only name and the runtime fields below keep the server's value when left out. Each prompt field holds up to 8,192 characters (policies after the Policy Shop bodies are filled in), greeting up to 600, and example_prompts up to six of 120 characters each. webhook_url= sets where tool calls go (a profile's webhook_url setting wins over it), and profile= picks which profile the config belongs to. The dashboard's read-only graft page renders each field as a labelled section so you can see exactly what the runtime is composing for every conversation.

#Runtime features & limits on ag.graft

Alongside the prompt fields, ag.graft(...) accepts runtime-feature and limit kwargs that tune memory, recap, context windows, and spend ceilings per graft. All of them are tri-state โ€” leave them as None (the default) to preserve whatever the server currently has, pass a concrete value to overwrite on the next sync. This mirrors how the name field already works: absent means "don't touch", present means "set explicitly".

  • memory_enabled: bool โ€” when True, each visitor gets long-term memory: after their turns (a burst of turns costs one pass) the Dreamer curates durable facts from the conversation, and later turns see the relevant ones in the prompt and can search and edit them with memory tools. Agents with memory=False and the private agent take no part. Default: False on fresh grafts. Turn on for any graft with returning visitors who benefit from cross-session memory.
  • recap_enabled: bool โ€” when True, a short "where you left off" summary is pre-generated after the conversation has been idle. Shown as a banner when the visitor reopens the thread, dismissed the moment they send their next message. Default: False.
  • recap_min_gap_minutes: int โ€” idle-time threshold before the recap sweep considers a conversation ready. Minimum 30 (the sweep floor); shorter values are rejected at sync time. Default: 30.
  • recap_message_pairs: int โ€” how many user + assistant pairs the recap summariser reads. Default: 10.
  • recap_min_message_pairs: int โ€” minimum pairs that must exist for a recap to be worth generating. Conversations shorter than this are skipped. Default: 3.
  • context_window_tokens: int โ€” overrides the context window ceiling used for conversation token profiling and accounting in the widget. It also sizes the private chat's history. Default: 32,000 tokens (valid range: 4,096 to 512,000).
  • max_message_chars: int โ€” hard character limit on every incoming user message. Rejects oversized input at the API boundary. Default: 10,000 chars (valid range: 1 to 10,000).
  • visitor_quota_usd: Decimal | float | int โ€” rolling spend ceiling in USD per visitor (or per shared allowance, see spend_as) across all conversations, including private chats and replies the visitor stopped early. Default: $5.00 (valid range: $0.01 to $10,000).
  • visitor_quota_window_days: int โ€” duration of the rolling spend window in days. Older usage rolls off continuously. Default: 7 days (valid range: 1 to 365).
  • image_uploads_enabled: bool โ€” when True, visitors can drop, paste or pick up to 5 images per message (a GIF is sent as a few still frames and counts as one). The widget offers it only when the agent answering next can see images; agents whose model can't get a text description of each image instead. Images are encrypted at rest under the visitor's key, and each description is charged to the visitor's quota. On Safari the host page's CSP needs 'wasm-unsafe-eval' (see Embedding the widget). Default: False.
  • voice_enabled: bool โ€” when True, the widget offers voice: replies read aloud, dictation, and hands-free listening for visitors who opt in. Reply text and visitor audio go to the speech providers (Deepgram, or the visitor's browser), and read-aloud is charged to the visitor's quota. When False the widget shows no voice controls and the speech endpoints refuse. Default: False.
  • followups_enabled: bool โ€” when True, each reply ends with two or three suggested next questions the visitor can click. Adds one cheap model call per turn, made before the reply finishes. Default: False.
  • palette: str โ€” the widget's accent colour, so it matches your app: buttons, links, and the face's eyes and juice. One of indigo, orchid, rose, coral, amber or jade (ag.PALETTES); each has a dark and a light variant that follows the widget's theme. An unknown name fails at ag.graft(...). Default: "indigo".
  • visitor_palette_enabled: bool โ€” when True, visitors can pick their own palette under Personalisation in the widget's settings, over yours. Their pick stays in their browser, and picking yours again puts them back on it. Default: False.
python
from decimal import Decimal

ag.graft(
    name="Acme",
    identity="You are Acme's in-app assistant.",
    # Runtime features & limits โ€” declare once, stays until you change it.
    context_window_tokens=32_000,
    max_message_chars=10_000,
    visitor_quota_usd=Decimal("5.00"),
    visitor_quota_window_days=7,
    memory_enabled=True,
    recap_enabled=True,
    recap_min_gap_minutes=60,        # only recap after an hour of silence
    recap_message_pairs=15,
    image_uploads_enabled=True,      # visitors can attach images
    voice_enabled=True,              # read aloud + talk instead of type
    followups_enabled=True,          # suggest questions after each reply
    palette="jade",                  # the widget's accent colour
    visitor_palette_enabled=True,    # visitors may pick their own
)
Typical production config: context window limit, spend quota, memory on, recap on, tuned for a chat audience that returns after a few hours.

#ag.policy(codename)

References a reusable system-prompt fragment from the AgentGraft Policy Shop. The sync command fetches the policy body by codename at push time and substitutes it into the composed policies text โ€” the runtime never sees the codename, only the resolved body.

Browse the catalogue at agentgraft.com/dashboard/policies/. Common codenames: agentgraft/no-hallucination, agentgraft/cite-sources, agentgraft/concise, agentgraft/secrets-redaction, agentgraft/mermaid-strict.

#Clickable references: ag.reference and ag.ref

Let the assistant link to objects in your app โ€” documents, projects, people โ€” as clickable chips inside its replies. Declare each type once with ag.reference(...), then have your tools return ag.ref(type, id, label) for every object they hand back. You can declare up to 50 types per graft; each type's description goes into every agent's prompt.

python
ag.reference(
    "block",
    label="Block",
    description="A document in the user's knowledge base.",
    url="/blocks/{id}",   # fallback when your JS doesn't handle the click
    icon="document",      # document | folder | user | calendar | link
)

@ag.tool
def search_blocks(user, query: str) -> list[dict]:
    """Search the user's blocks."""
    return [
        {"ref": ag.ref("block", b.id, b.title), "snippet": b.snippet}
        for b in Block.objects.search(user, query)
    ]

ag.ref returns text like [Q3 Plan](ref:block/42). The assistant is told to paste refs verbatim, and the widget renders each one as a chip. Clicking a chip dispatches a cancelable agentgraft:reference event on window. Call preventDefault() to open the object in-app; otherwise the widget navigates to url with {id} filled in. In fullscreen or on mobile, the widget collapses after a click so the object isn't hidden behind it.

A type's name is snake_case, up to 32 characters; label (up to 60) and description (up to 300) are required. url must contain {id} and be a same-site path or an https:// URL; leave it out when your JavaScript always handles the click. An id may be any value whose string form is 1โ€“128 letters, digits or . _ ~ @ : -, so integer keys, UUIDs and composite ids like block@alice:k3f9 all work; / is not allowed. Labels longer than 80 characters are shortened. Each check fails at import with a ValueError.

javascript
window.addEventListener("agentgraft:reference", (event) => {
  const { type, id, label } = event.detail;
  if (type !== "block") return;
  event.preventDefault();   // skip the url fallback
  openBlock(id);            // your app's own navigation
});

#Multiple profiles

One host app can run several chat experiences side by side. Add another entry to AGENTGRAFT['profiles'], decorate the tools and agents for it with profile="<name>", and the registries stay physically separate inside the SDK. A marketing tool can never be called against an authenticated user, and vice versa.

python
# settings.py
AGENTGRAFT = {
    "config_module": "myapp.agentgraft_config",
    "profiles": {
        "default": {  # the in-app helper, authenticated users
            "api_base":       "https://agentgraft.com",
            "api_key":        os.environ["AGENTGRAFT_API_KEY"],
            "public_key":     os.environ["AGENTGRAFT_PUBLIC_KEY"],
            "graft_id":       os.environ["AGENTGRAFT_GRAFT_ID"],
            "webhook_secret": os.environ["AGENTGRAFT_WEBHOOK_SECRET"],
        },
        "marketing": {  # the public landing-page bot, anonymous visitors
            "api_base":       "https://agentgraft.com",
            "api_key":        os.environ["AGENTGRAFT_MARKETING_API_KEY"],
            "public_key":     os.environ["AGENTGRAFT_MARKETING_PUBLIC_KEY"],
            "graft_id":       os.environ["AGENTGRAFT_MARKETING_GRAFT_ID"],
            "webhook_secret": os.environ["AGENTGRAFT_MARKETING_WEBHOOK_SECRET"],
        },
    },
}
python
# myapp/agentgraft_config.py
@ag.tool                            # default profile, authenticated
def list_my_datasets(user: User): ...

@ag.tool(profile="marketing")       # marketing profile, anonymous
def what_is_acme(user: dict): ...

@ag.agent(entry=True, tools=[list_my_datasets])
def helper(): ...

@ag.agent(profile="marketing", entry=True, tools=[what_is_acme])
def landing_bot(): ...

#manage.py agentgraft_sync

The sync command serialises every registry the config module populated and POSTs the bundle to the matching graft's /api/v1/admin/grafts/<id>/sync/ endpoint. The push is atomic on the server side โ€” either every tool, agent, and prompt change lands together, or none of them do.

bash
# Sync every declared profile (default behaviour)
python manage.py agentgraft_sync

# Restrict to one profile
python manage.py agentgraft_sync --profile marketing

# Print the payload, don't send it (needs no api_key or graft_id)
python manage.py agentgraft_sync --dry-run

# CI-friendly: don't crash on missing credentials
python manage.py agentgraft_sync --skip-if-unconfigured

# Override retry count on flaky networks (default: 3)
python manage.py agentgraft_sync --retries 5

The --skip-if-unconfigured flag is the one most deployment pipelines need โ€” see the Deployment page for the full Railway preDeploy story. The TL;DR is that it lets your first deploy succeed before you've pasted credentials into env vars, and skips, with a warning in the deploy log, any profile whose api_key or graft_id isn't set yet or whose registry is empty, instead of failing the build. --retries covers the Policy Shop fetches as well as the push, which is declarative, so repeating it is safe. A dry run touches the network only to resolve ag.policy(...) references, which needs api_base.

#The webhook view

The Django adapter ships a single view that handles every incoming tool call. Mount its URL include and the SDK registers /agentgraft/webhook/ and /agentgraft/webhook/<profile>/ automatically.

python
# urls.py
from django.urls import include, path

urlpatterns = [
    path("agentgraft/", include("agentgraft.django.urls")),
]

The view verifies the HMAC signature on every incoming request, rejects requests whose signed timestamp is more than 5 minutes from the host clock in either direction (replay protection), looks up the matching tool by name in the profile's registry, checks the arguments fit it, runs it with the resolved user through the profile's tool-call hooks, and returns the JSON-serialised result. You don't write any view code โ€” the SDK handles the entire request lifecycle.

Each failure has its status: a bad signature, or a signed timestamp that is missing or stale, is a 401; malformed JSON or arguments that don't fit the tool a 400; an unknown tool a 404; a user loader that raises a 403; a tool or hook that raises a 500. AgentGraft shows the model a failed call's message, so an exception from your code is logged on your side (agentgraft.webhook logger, with its traceback) and answered with Tool 'x' failed (request req_โ€ฆ).: search your logs for the request id. To tell the model why a call failed, raise ag.WebhookError(status, "message"), whose message is sent as it is. Set the profile's "detailed_errors": True to send exception text instead. The view is CSRF-exempt and accepts POST only.

#Tool-call hooks

@ag.on_tool_call registers a hook that wraps every tool call a profile's webhook runs: the place for what applies to all your tools at once, like an audit trail, metrics or a kill switch. The hook gets the call and proceed; calling proceed() runs the rest of the chain and the tool and returns the result, and whatever the hook returns is the call's result.

python
import time

import agentgraft as ag


@ag.on_tool_call
def audited(call: ag.ToolCall, proceed):
    started = time.monotonic()
    outcome = "error"
    try:
        result = proceed()
        outcome = "ok"
        return result
    finally:
        AuditLog.objects.create(
            user=call.user,
            agent=call.agent,
            tool=call.tool,
            request_id=call.request_id,
            outcome=outcome,
            duration_ms=round((time.monotonic() - started) * 1000),
        )
An audit trail of every agent action, in one place.
  • call is an ag.ToolCall: tool, arguments (a read-only view), user (what your loader returned), user_external_id, is_anonymous, private, agent (the agent that made the call, by its name in your config), request_id, profile, conversation_id (the conversation whose turn made the call; None from the private chat) and turn_key (the turn_key your server sent with that turn's send_message; None for a turn sent without one).
  • A hook can act around the call, replace its result, answer without running the tool (return without calling proceed()), or refuse it: raise ag.WebhookError(403, "search is disabled") sends that status and message back, and the model sees the error (a 502, 503 or 504 makes AgentGraft retry the call once). Any other exception from a hook is a 500.
  • Hooks run only for calls that reach a tool: verified, with the user loaded and arguments that fit. The first registered is outermost; each profile has its own (@ag.on_tool_call(profile="public")).
  • ag.current_tool_call() returns the call in progress to hooks, the tool and anything they call, and None outside a webhook call.

#The template tag

One tag, in any Django template (with "agentgraft.django" in INSTALLED_APPS):

html+django
{% load agentgraft %}
{% agentgraft_widget %}

By default it renders the default profile. Pass profile="marketing" to render a different profile on a different page. The tag emits a single <script type="module"> element with the public key, the API base, the visitor's id and a visitor token for it signed with the matching profile's webhook secret, data-anonymous, and data-locale (the request's active language, so the widget speaks it). A signed-in user is user:{pk}. A logged-out visitor gets the placeholder browser:* and a token for the anonymous grant, the same on every page: the widget picks a random id for the browser, so rendering creates no session, sets no cookie, and the page is safe to cache for less than the token's lifetime. The token holds for 24 hours from the render (a profile's visitor_token_ttl, in seconds up to 7 days, changes that) and every render signs a fresh one, so a page left open longer needs a reload.

The tag reads request.user, so keep the request context processor on; without a request every visitor renders as logged out. In an async def view, await request.auser() before rendering.

#Rendering the widget tag yourself

Without the Django tag, write the same attributes yourself. data-user-hmac is a visitor token for the id, signed with the webhook secret (its format is on the Wire protocol page); for a logged-out visitor it is a token for the grant agentgraft:anonymous-visitor:v1 (ag.ANONYMOUS_VISITOR_GRANT), never the placeholder browser:* (ag.ANONYMOUS_VISITOR_ID). Sign a fresh one with every page you render.

python
import agentgraft as ag

# Logged out: data-user-id="browser:*" data-user-hmac="{signature}" data-anonymous="true"
signature = ag.compute_user_hmac(
    secret=webhook_secret, user_external_id=ag.ANONYMOUS_VISITOR_GRANT
)

# Logged in: data-user-id="user:42" data-user-hmac="{signature}" data-anonymous="false"
signature = ag.compute_user_hmac(secret=webhook_secret, user_external_id="user:42")
# "v2.1796000000.9f4d2e3a...": good for 24 hours; ttl_s=... (up to 7 days) to change it

#Programmatic Chat & Omnichat (Client)

Beyond the drop-in browser widget, AgentGraft provides a first-class programmatic client (agentgraft.Client) with zero external dependencies. It supports two primary integration models:

  • Autonomous Omnichat (zero thread management needed)
  • Custom UI & Thread Lifecycle (for custom frontends & mobile apps)

#1. Autonomous Omnichat (Slack, WhatsApp, API Workers)

For most backend integrations (Slack bots, WhatsApp handlers, SMS bots, Celery tasks, or backend API proxies), you do not need to manage or store conversation IDs. Passing auto_route=True lets AgentGraft handle the entire lifecycle autonomously:

python
from agentgraft import Client

client = Client.from_profile("default")

# One line to chat โ€” AgentGraft matches existing topic threads,
# pre-fetches long-term memories, dispatches tools, and auto-titles the thread.
response = client.chat(
    user_id="slack:U123456",
    message="What are my top 3 active projects?",
    auto_route=True,
    visitor_name="Alice",
)

print(f"Assigned Thread: {response['conversation_id']}")
print(f"Assistant: {response['text']}")

#2. Explicit Thread Continuity & Streaming

When you already have a conversation in flight or want real-time token streaming, pass the conversation_id explicitly:

python
# Real-time SSE streaming inside a specific thread
for event in client.stream_chat(
    user_id="slack:U123456",
    conversation_id=response["conversation_id"],
    message="Can you detail project #2?",
):
    if event["type"] == "token":
        print(event["text"], end="", flush=True)
    elif event["type"] == "tool_call":
        print(f"\n[Calling tool: {event['name']}]")
    elif event["type"] == "done":
        print("\n[Finished]")

stream_chat is lazy: nothing is sent until you start iterating, and every failure (auth, HTTP status, network, a stream cut off or silent for longer than timeout) is raised as an ag.APIError from the loop, not the call, so keep the loop inside your try. It takes turn_key as send_message does: sent again, a finished turn runs nothing and streams back its saved reply, ending in a done with "replayed": true; one still running, or one that never finished, is an ag.ConflictError. Besides token (text) and tool_call (name, arguments), you may see tool_result, agent_changed (name) after a handoff, title, followups (questions), and last done, which carries the saved reply (message_id, text, agent_name, tokens and cost) and the visitor's quota. Ignore types you don't know: new ones may be added.

#3. Custom UI & Thread Lifecycle Management

If you are building your own custom user interface (e.g. an iOS/Android mobile app, custom React/Vue chat widget, or admin dashboard), Client gives you full programmatic control over conversations, messages, and feedback:

python
# List all threads for a user
threads = client.list_conversations(user_id="user:42")

# Fetch full message history of a thread
messages = client.get_messages(user_id="user:42", conversation_id="convo-uuid")

# Semantic + substring search across visitor history
results = client.search_messages(user_id="user:42", query="quarterly invoice")

# Submit RLHF thumbs up/down rating on an assistant message
client.submit_feedback(user_id="user:42", message_id="msg-uuid", positive=True)

# Programmatic long-term memory CRUD
memories = client.list_memories(user_id="user:42")
client.create_memory(user_id="user:42", content="Prefers monthly billing")
client.update_memory(user_id="user:42", memory_id="fact-uuid", content="Prefers annual billing")
client.delete_memory(user_id="user:42", memory_id="fact-uuid")

#4. Running agents from your server

Your server can run agents with no person in the chat, such as bots your users hire. Give each bot an id of its own, start its conversations on the agent it is, brief it each turn, and have it spend from the allowance of the user it works for:

python
client = Client.from_profile("default")  # with api_key, public_key and webhook_secret

reply = client.chat(
    user_id="bot:researcher-12",  # the bot, a visitor of its own
    message="It's Monday: anything new on embeddings?",
    agent="researcher",           # start on this agent, not the entry point
    instructions=job_text,        # this turn's brief, after the agent's role
    spend_as="user:42",           # spend from the allowance of the user it works for
)

# The allowance, and what each spender took from it
usage = client.get_usage("user:42", actors=["user:42", "bot:researcher-12"])

# The bot's conversations and memory go; what it spent still counts
client.delete_user_data("bot:researcher-12")
  • agent, instructions and spend_as are for your server only. agent goes to create_conversation and chat; instructions to send_message, stream_chat and chat; spend_as to all of those and route_message. They need the API key, which the client sends in X-AgentGraft-Server-Key with those calls alone; without it the client raises ValueError before sending anything. A page asking for them gets a 403, and a wrong key a 401.
  • agent starts a new conversation on any agent but the private one, and that agent answers every turn until it hands off.
  • instructions go into the system prompt of every agent in that turn, after its role. They are not stored: send them with each turn they should hold for, up to 20,000 characters.
  • spend_as points the visitor at another visitor's allowance until a call sets it again. The quota, its 429 and the turns in flight are then that allowance's, so a user and all their bots share one. Pass the visitor's own id to give them back their own. Allowances don't chain, and the pointer belongs to the visitor, not the call: give every bot an id of its own rather than reusing one for several users.
  • get_usage returns {"quota": {...}, "actors": {...}}: the allowance as the widget reads it (used_usd, remaining_usd, quota_usd, next_refill_at, โ€ฆ) and what each id in actors (up to 100) spent from it in the quota window, as a decimal string with six places. An id that spent none of it reads "0.000000". It needs no API key.
  • delete_user_data deletes the visitor and every conversation, message and memory of theirs, as the widget's "delete my data" does, and returns {"deleted": n}, the number of conversations removed. What they spent stays on the allowance it came from until it leaves the window.
  • turn_key on send_message is your own id for the turn (up to 64 characters), so a send you retry never runs it twice. A finished turn sends back its saved reply with "replayed": True; one still running is a 409; one that started and never finished is a 409 whose APIError.code is "turn_unfinished", and nothing runs, since its tools may have done things: carry on with a new key. The same key with other words is a 400. Each of its tool calls carries the key as ToolCall.turn_key. stream_chat takes it too, and chat() passes it, with budget_s and reply_s, to the send_message it sends the turn with: to retry a chat() safely, pass the conversation_id the first attempt used.
  • budget_s on send_message gives a turn no one watches a deadline (up to 480 s): its agents call your tools for that long, then have reply_s (30 s by default, up to 60) for their last reply, and are stopped at the sum. Past the budget a tool call returns at once, telling the model to reply, and never reaches your webhook. The reply then has "cut_short": True, as its message does in get_messages; its text is empty if it was stopped before it said anything, and what it used is still charged. The client waits budget_s + reply_s + 15 seconds.

#A turn from your server, safely retried

A key keeps a turn from running twice in one conversation, and a chat() without a conversation_id creates or routes to one each time, so a bot turn you may need to resend goes in two steps: create the conversation, then send to it. Resend with the same turn_key after a timeout to collect the reply instead of running the turn twice.

python
convo = client.create_conversation(
    "bot:researcher-12", agent="researcher", spend_as="user:42"
)
reply = client.send_message(
    "bot:researcher-12",
    convo["id"],
    "Anything new on embeddings?",
    instructions=job_text,
    turn_key=f"job-{job.pk}",  # the same key on every retry of this turn
    budget_s=300,              # tools for up to 5 minutes, then 30 s to reply
)
if reply.get("cut_short"):
    ...  # it hit the deadline: the text may be partial or empty

#5. Client reference

python
from agentgraft import APIError, Client

client = Client(
    api_base="https://agentgraft.com",
    api_key=None,         # sync, and the calls only your server may make
    public_key=None,      # chat calls
    webhook_secret=None,  # chat calls: signs the user_id you pass
    timeout=120,          # socket timeout per request, in seconds
    max_retries=3,
)
client = Client.from_profile("default")      # from AGENTGRAFT["profiles"] (needs Django)
client = Client.from_env(prefix="AGENTGRAFT_")  # API_BASE, API_KEY, PUBLIC_KEY, WEBHOOK_SECRET
client = Client.from_profile("default", timeout=30, max_retries=1)  # both factories take these
  • Chat calls need public_key and webhook_secret; the sync needs api_key. A missing one raises ValueError before anything is sent.
  • Every failure is an ag.APIError: status_code (0 when no complete reply came, such as a network error or timeout), body, and code (the error body's code, such as "turn_unfinished", or "").
  • Its subclasses say what went wrong, so except APIError still catches them all: APIConnectionError (status 0) and its APITimeoutError, AuthenticationError (401 and 403, an expired visitor token included), NotFoundError (404), ConflictError (409), RateLimitError (429, with retry_after in seconds or None) and ServerError (5xx). Any other status, such as a 400, is a plain APIError.
  • With the default timeout, send_message and chat wait up to 630 s, since a non-streaming turn replies only once it is over; a timeout you pass applies as it is, and None waits as long as it takes. A turn that timed out may still be running: its reply lands in get_messages.
  • Reads, deletes and the sync push are retried on network errors, 429 and 5xx (max_retries), with back-off, waiting out a Retry-After of up to 60 s. Sends and creates are never retried, since they may have reached the server.
  • Redirects are never followed, so credentials never reach another address: a 3xx raises APIError. A plain http:// api_base to another machine warns.
  • user_id, visitor_name and visitor_timezone travel in headers, which carry Latin-1 only: a user_id outside it raises ValueError (use an ASCII id such as the primary key), and a visitor_name outside it is dropped with a warning.

Every chat method takes user_id first. Beyond those above:

  • create_conversation(user_id, *, title="", agent="", spend_as="") โ€” returns the conversation, with its id.
  • list_conversations(user_id) โ€” pinned threads, then the rest, then archived ones, each most recently active first.
  • get_conversation, rename_conversation(user_id, conversation_id, title) and delete_conversation (with all its messages).
  • route_message(user_id, message) โ€” the Thread Router's decision: action ("existing" or "new"), conversation_id, preview_title and tier.
  • send_message(user_id, conversation_id, message, *, instructions, spend_as, turn_key, budget_s, reply_s) โ€” one non-streaming turn; chat() is built on it.
  • create_memory(user_id, content, *, category="contextual") and update_memory(user_id, memory_id, content, *, category=None), where a category is identity, contextual or episodic.
  • submit_feedback(user_id, message_id, positive, *, comment="").
  • Every chat method also takes visitor_name and visitor_timezone (an IANA name such as Europe/London).
  • sync_graft(graft_id=..., payload=...) and fetch_policy(codename) are what agentgraft_sync uses.

#6. AsyncClient

For asyncio code, ag.AsyncClient has every Client method as a coroutine, with the same arguments, errors and return values, and stream_chat as an async iterator. It runs the same standard-library transport on worker threads (asyncio.to_thread), so the SDK still needs no HTTP library, and calls run concurrently. AsyncClient.from_profile, from_env and wrapping(client) build one; .sync is the Client it wraps. To stop reading a stream early, wrap it in contextlib.aclosing(...): a break alone leaves an async iterator, and its connection, open until it is garbage-collected.

python
from agentgraft import AsyncClient

client = AsyncClient.from_profile("default")

reply = await client.chat("slack:U123456", "What's pending?", auto_route=True)

async for event in client.stream_chat("user:42", reply["conversation_id"], "And the first?"):
    if event["type"] == "token":
        print(event["text"], end="", flush=True)

#Without Django

The core (registry, decorators, schema, webhook handler) works without Django. Import your config module yourself at startup, so the decorators run, and call ag.handle_webhook from your framework's view. It returns {"result": ...} or raises ag.WebhookError with status_code and message. Pass it the X-AgentGraft-Signature-V2 header (ag.SIGNATURE_HEADER): from SDK 0.18 the legacy X-AgentGraft-Signature is refused with a 401. The same pattern works for FastAPI, Starlette or raw WSGI.

python
import os

from flask import request

import agentgraft as ag
import myapp.agentgraft_config  # noqa: F401 โ€” runs the decorators


@app.post("/agentgraft/webhook/")
def agentgraft_webhook():
    try:
        result = ag.handle_webhook(
            body=request.get_data(),
            signature=request.headers.get("X-AgentGraft-Signature-V2", ""),
            webhook_secret=os.environ["AGENTGRAFT_WEBHOOK_SECRET"],
            profile="default",
            detailed_errors=False,  # True sends exception text to the model
        )
    except ag.WebhookError as exc:
        return {"error": exc.message}, exc.status_code
    return result, 200

#Testing

Tools are plain Python functions โ€” call them directly in tests with a stub user object. The agentgraft.testing module gives you a pytest fixture and two utilities for testing the registry and schema in addition to raw function logic (it needs pytest installed).

python
# conftest.py โ€” make ag_reset available project-wide
pytest_plugins = ["agentgraft.testing"]
python
from agentgraft.testing import call_tool, tool_schema

def test_get_order_returns_correct_fields(db):
    user = make_test_user()
    result = call_tool(get_order, user, order_id="abc123")
    assert result["id"] == "abc123"

def test_get_order_schema_has_required_order_id():
    schema = tool_schema(get_order)
    assert "order_id" in schema["required"]
    assert schema["properties"]["order_id"]["description"] != ""

def test_list_orders_plain_call(db):
    # Tools are plain functions โ€” no framework required
    user = make_test_user()
    orders = list_orders(user, status="pending")
    assert all(o["status"] == "pending" for o in orders)

call_tool(fn_or_name, user, *, profile="default", **kwargs) โ€” call a registered tool by function reference or string name, with user injected as the first argument, exactly as the webhook handler would. Accepts the same **kwargs the LLM would supply. The tool runs alone, without the profile's tool-call hooks; test a hook by calling it with an ag.ToolCall and a proceed of your own. It raises KeyError for an unknown name, TypeError for arguments that don't fit, and ag.WebhookError for a Pydantic argument that doesn't validate (the webhook's 400).

tool_schema(fn_or_name, *, profile="default") โ€” return the JSON schema dict the SDK would push at sync time. Use it to assert that parameter descriptions, types, and required fields are exactly right before they reach production.

ag_reset fixture โ€” wipes every profile's registry before and after the test. Use it only in tests that declare their own tools, agents or hooks inside the test. Your config module registers once, at startup, and is not imported again, so after a reset tool_schema raises KeyError for your real tools, and call_tool calls them as plain functions.