agentgraft
Python SDK for AgentGraft. Define your chat configuration in code, sync it to the hosted service, and embed a chat widget on your site with one template tag.
pip install agentgraft # core SDK (framework-agnostic)
pip install agentgraft[django] # + Django management command, webhook view, template tag
The PyPI distribution and the import name are both agentgraft. Django
glue lives at agentgraft.django; everything else is framework-agnostic.
How it fits together
Three actors:
- End user — talks to the widget in their browser.
- Host app — your Django project. Owns user identity, owns the data, owns tool execution.
- AgentGraft — hosted service. Owns the chat UI, the LLM loop, and the conversation storage.
The SDK is the bridge. You write one Python file declaring your tools, agents, and prompt context. You run one command to push that file to AgentGraft. You drop one template tag wherever the chat should appear. When the LLM wants to call a tool, AgentGraft signs an HTTP request to your host app's webhook URL; the SDK receives it, verifies the signature, runs your function, returns the result.
The host app's database is never read by AgentGraft directly. AgentGraft only ever sees tool schemas — never tool implementations.
Quickstart (Django)
1. Install
pip install agentgraft[django]
2. Add to INSTALLED_APPS
# settings.py
INSTALLED_APPS = [
# ...
"agentgraft.django",
]
3. Configure
# settings.py
AGENTGRAFT = {
"config_module": "myapp.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"],
},
},
}
The four credentials come from creating a graft on AgentGraft. The
api_key is shown only once at creation — store it as a secret.
4. Mount the webhook URL
# urls.py
from django.urls import include, path
urlpatterns = [
# ...
path("agentgraft/", include("agentgraft.django.urls")),
]
This exposes POST /agentgraft/webhook/ for tool dispatches. Configure
that URL as your graft's webhook_url (either at graft creation or
inside ag.graft(webhook_url=...)).
5. Write the config
Create myapp/agentgraft_config.py:
import agentgraft as ag
from myapp.models import User
@ag.user_loader
def load_user(external_id: str) -> User:
return User.objects.get(pk=external_id.removeprefix("user:"))
@ag.tool
def list_datasets(user: User) -> list[dict]:
"""List the user's datasets."""
return list(user.datasets.values("id", "name"))
@ag.tool
def get_dataset(user: User, dataset_id: int) -> dict:
"""Fetch one dataset by id."""
ds = user.datasets.filter(pk=dataset_id).first()
return {"id": ds.id, "name": ds.name} if ds else {}
@ag.agent(entry=True, tools=[list_datasets, get_dataset])
def helper():
"""You help users explore their datasets. Be concise."""
ag.graft(
name="MyApp",
identity="You are MyApp's assistant.",
voice="Be direct. Skip filler.",
policies=[
ag.policy("agentgraft/no-hallucination"),
ag.policy("agentgraft/concise"),
],
greeting="Ask me about your datasets.",
example_prompts=[
"How many datasets do I have?",
"Show me the most recent one",
],
)
6. Sync
python manage.py agentgraft_sync --dry-run # inspect the payload
python manage.py agentgraft_sync # push it
7. Embed the widget
In any Django template:
{% load agentgraft %}
{% agentgraft_widget %}
That's the whole integration for browser embedding. In an async def
view, await request.auser() before rendering: the tag then uses that
user as it is (it otherwise looks the user up on a worker thread).
Programmatic Chat & Omnichat (Client)
Beyond the drop-in web widget, the SDK provides agentgraft.Client — a stdlib-only HTTP client to interact with AgentGraft programmatically. Use it to build Slack bots, WhatsApp / Discord assistants, mobile apps, customer support bots, or custom frontends while reusing the same tools, multi-agent workflows, and persistent memory graph.
from agentgraft import Client
# In Django: auto-load from settings.py AGENTGRAFT['profiles']['default']
client = Client.from_profile("default")
# Or from environment variables: AGENTGRAFT_API_BASE (required),
# AGENTGRAFT_API_KEY, AGENTGRAFT_PUBLIC_KEY and AGENTGRAFT_WEBHOOK_SECRET
# (pass prefix= to read others):
# client = Client.from_env()
# ── Mode 1: Autonomous Omnichat (Slack, WhatsApp, API Workers) ────────
# Zero thread management needed. AgentGraft matches past topics, auto-creates
# threads, pre-fetches memory facts, and auto-titles conversations.
response = client.chat(
user_id="slack:U987654",
message="What are my top pending tasks?",
auto_route=True,
visitor_name="Alice",
)
print(f"Conversation ID: {response['conversation_id']}")
print(f"Assistant: {response['text']}")
# ── Mode 2: Targeted Thread Continuity & Real-Time Streaming ───────────
for event in client.stream_chat(
user_id="slack:U987654",
conversation_id=response["conversation_id"],
message="Can you break down task #1 into subtasks?",
):
if event["type"] == "token":
print(event["text"], end="", flush=True)
elif event["type"] == "done":
print("\n[Done]")
# ── Mode 3: Custom UI & Thread Lifecycle Management ────────────────────
# Building custom mobile apps, React widgets, or admin dashboards:
threads = client.list_conversations(user_id="user:42") # pinned, others, archived
messages = client.get_messages(user_id="user:42", conversation_id="convo-uuid")
search_hits = client.search_messages(user_id="user:42", query="invoice")
client.rename_conversation(user_id="user:42", conversation_id="convo-uuid", title="Invoices")
client.delete_conversation(user_id="user:42", conversation_id="convo-uuid")
client.submit_feedback(user_id="user:42", message_id="msg-uuid", positive=True)
# 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")
Every failure is raised as agentgraft.APIError: status_code is the
HTTP status, or 0 when no complete reply came (network errors, timeouts,
a connection dropped mid-reply or mid-stream). Its subclasses say what
went wrong, so except APIError still catches them all:
| Error | When |
|---|---|
APIConnectionError |
No complete reply (status_code 0): connection refused or dropped, DNS, TLS, a stream cut off or ended before its done or error event |
APITimeoutError |
A subclass of APIConnectionError: nothing came for timeout seconds. The request may have reached the server |
AuthenticationError |
401 / 403: a bad public key, visitor token or server key, an expired visitor token, a call only your server may make |
NotFoundError |
404 |
ConflictError |
409: the conversation is busy, or a turn_key is still running; code == "turn_unfinished" when its turn never finished |
RateLimitError |
429: the visitor's quota is spent, or too many requests; retry_after is the Retry-After in seconds, or None |
ServerError |
5xx |
Any other status (a 400, a 413, a redirect) is a plain APIError.
from agentgraft import ConflictError, RateLimitError
try:
reply = client.send_message("bot:7", convo_id, text, turn_key=key)
except ConflictError as exc:
if exc.code == "turn_unfinished":
... # it started and never finished: carry on with a new key
except RateLimitError as exc:
retry_in = exc.retry_after
- Timeouts.
Client(timeout=120)is the socket timeout of each request. With that default,send_messageandchatwait up to 630 s instead, the longest a turn can hold its conversation: a non-streaming turn replies only once it is over. Atimeoutyou pass applies to turns too, andtimeout=Nonewaits as long as it takes. A turn that times out may still be running; its reply lands inget_messages, and resending meanwhile gets a 409. Preferstream_chatfor anything interactive. - Streaming is lazy.
stream_chatsends nothing until you start iterating, and its errors (auth, HTTP status, network) are raised from the loop, not the call. Keep the loop inside yourtry. A turn's stream ends with adoneor anerrorevent: one that ends without either was cut off, and raisesAPIConnectionErrorafter the events it got, so a reply that stops short is never taken for a whole one. - A streamed turn can be keyed.
stream_chat(..., turn_key="...")takes a key assend_messagedoes: sent again, a finished turn runs nothing and streams back its saved reply, ending in adonewith"replayed": True; one still running, or one that never finished, is aConflictError; the same key with other words a400. - Visitor tokens. Each chat call signs
user_idwithwebhook_secretinto a visitor token (v2.<expiry>.<hex>) good for an hour, signed afresh for every request, inX-AgentGraft-User-HMAC. - Retries. Reads, deletes and the sync push are retried on network
errors, 429 and 5xx with jittered exponential back-off (
max_retries=3). ARetry-Afterin seconds, up to 60, is waited out; a longer one is raised at once. Other writes (sending a message, creating a conversation) are never retried, since they may have reached the server. - Identity headers.
user_id,visitor_nameandvisitor_timezonetravel in HTTP headers, which carry Latin-1 text only. Auser_idoutside that (or with line breaks) raisesValueErrorbefore anything is sent: use an ASCII id such as the primary key. Avisitor_nameoutside Latin-1 (e.g. "李雷") is left out with a warning, so the visitor keeps the name AgentGraft already has; control characters are stripped from it, as the server would. - Credentials stay on HTTPS and off redirects. The client warns when
api_baseis plainhttp://to anything but this machine. Redirects are never followed: a3xxreply raises anAPIErrornaming where it pointed, so setapi_baseto the address the API answers on.
AsyncClient
For asyncio code, AsyncClient has every Client method as a
coroutine, with the same arguments, errors and return values, and
stream_chat as an async iterator:
from agentgraft import AsyncClient
client = AsyncClient.from_profile("default", timeout=60) # or AsyncClient(api_base=..., ...)
reply = await client.chat("slack:U987654", "What's pending?", auto_route=True)
async for event in client.stream_chat("user:42", reply["conversation_id"], "And the first one?"):
if event["type"] == "token":
print(event["text"], end="", flush=True)
It runs the same stdlib transport on worker threads (asyncio.to_thread),
so the SDK still needs no HTTP library; calls run concurrently, one thread
each. AsyncClient.wrapping(client) sends through a Client you already
have, and .sync is the Client it wraps. Like the sync one, stream_chat
sends nothing until the first event is awaited. Cancelling a task
mid-stream shuts its connection down at once, so the worker thread waiting
on the read is freed then, not at the next event or the timeout. Leaving
an async for early (break) doesn't close an async iterator by itself:
Python closes it only when it is garbage-collected, holding the connection
(and the conversation) until then. To stop reading early, wrap it:
import contextlib
async with contextlib.aclosing(client.stream_chat("user:42", convo_id, "Hi")) as events:
async for event in events:
if event["type"] == "done":
break
Running agents from your server
Your server can run agents with no person in the chat: a bot your users hire, a scheduled job. Give the 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:
client = Client.from_profile("default") # with api_key, public_key, 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
)
usage = client.get_usage("user:42", actors=["user:42", "bot:researcher-12"])
# {"quota": {...}, "actors": {"user:42": "0.410000", "bot:researcher-12": "0.120000"}}
client.delete_user_data("bot:researcher-12") # its threads and memory go; its spend still counts
- Only your server.
agent,instructions,modelandspend_asneedapi_key, which the client sends inX-AgentGraft-Server-Keywith those calls only. Without it the client raisesValueErrorbefore sending anything. The server refuses them from a page (403) and refuses a wrong key (401). agentstarts a conversation thatcreate_conversationorchatmakes on any of the graft's agents but the private one. It answers every turn until it hands off. A conversationchatroutes to or is given keeps its own agent.instructionsgo into the system prompt of every agent in that turn, after its role, under "Instructions for This Turn". They are not stored: send them with each turn they should hold for. Up to 20,000 characters.modelonsend_message,stream_chatandchatoverrides the active agent's configured model for that turn only (e.g."auto:quality"), so a bot or server-driven conversation can switch model tiers between turns without starting a new conversation. Up to 64 characters.spend_aspoints the visitor at another's allowance, from that call on, until a call sets it again (the visitor's own id gives them back their own). Their quota, and its429, is then that allowance's, and turns in flight are held against it, so the user and all their bots share one allowance. Allowances don't chain: the other visitor's own is used, whatever theirs points at. It belongs to the visitor, not the call, so give every bot an id of its own rather than reusing one for several users.get_usagereads the allowance a visitor spends from and what each id inactorsspent from it in the quota window, as decimal strings with six places. Ask about the allowance's own visitor under their own id. An id that spent none of it reads"0.000000". Up to 100 ids. Any visitor may read their own allowance; it needs no key.delete_user_datadeletes the visitor and every conversation, message and memory of theirs, as the widget's "delete my data" does. What they spent stays on the allowance it came from until it leaves the window.turn_keyonsend_messageis your own id for the turn (up to 64 characters), so a send you retry never runs it twice in the conversation. A finished turn sends back its saved reply, marked"replayed": True. One still running is a409. One that started and never finished (its run stopped part-way) is a409whoseAPIError.codeis"turn_unfinished": nothing runs, since its tools may have done things, so carry on with a new key. The same key with other words is a400. Each tool call the turn makes carries the key, asToolCall.turn_key.budget_sonsend_messagegives a turn no one watches a deadline, up to 480 s. Its agents call your tools for that long, then havereply_s(default 30, 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. A call still waiting on your webhook when the budget runs out is abandoned: your tool may still finish, but the model is told time is up and never sees its result. The reply then has"cut_short": True, as its message does inget_messages; if it was stopped before it said anything, its text is empty, and what it used is still charged. The conversation's lock is renewed while the turn runs and lasts the deadline and 30 s past its last renewal, so a run that died frees it then, and the client waitsbudget_s + reply_s + 15s.turn_key,budget_sandreply_sneed noapi_key.chattakes all three and passes them to thesend_messageit sends the turn with;stream_chattakesturn_key. A key keeps a turn from running twice in one conversation, so to retry achatsafely pass theconversation_idthe first attempt used: without it a retry creates or routes again. For a bot turn you may need to resend, create the conversation withcreate_conversation(agent=...)first, then send to it.- Mark the agents your server runs
unattended=True(see@ag.agent), give a bot anidentityof its own, and setmemory=Falseon one other people read.
These need an AgentGraft server that knows them. An older one ignores
agent, instructions and spend_as, and answers get_usage with a
404. It also ignores an agent's identity and memory: the agent
then keeps the graft's identity, and its memory stays on. One that
predates turn_key and budget_s ignores them: it runs every send,
with no deadline. One that predates turn_key on streams runs a keyed
streamed turn every time.
Settings reference
Every key lives under the AGENTGRAFT dict in settings.py.
AGENTGRAFT = {
"config_module": "myapp.agentgraft_config", # optional, default: "agentgraft_config"
"profiles": {
"default": {
"api_base": "https://agentgraft.com",
"api_key": "sk_live_...",
"public_key": "pk_live_...",
"graft_id": "uuid",
"webhook_secret": "whsec_...",
"webhook_url": "https://myapp.com/agentgraft/webhook/", # optional
},
},
}
| Key | Required by | Description |
|---|---|---|
config_module |
AppConfig.ready |
Dotted path to your config module. Defaults to "agentgraft_config" (a top-level agentgraft_config.py). |
profiles.<name>.api_base |
sync, widget | Origin of the AgentGraft service. |
profiles.<name>.api_key |
sync, Client calls your server makes with agent, instructions or spend_as |
Bearer token for /api/v1/admin/grafts/{id}/sync/, and the X-AgentGraft-Server-Key of server-only chat calls. Shown once at graft creation. |
profiles.<name>.public_key |
widget, every Client chat call |
Browser-safe key embedded in the widget script tag. |
profiles.<name>.graft_id |
sync, widget | UUID of the graft. |
profiles.<name>.webhook_secret |
webhook view, widget HMAC, every Client chat call (it signs user_id) |
HMAC signing secret used by both AgentGraft (signing tool dispatches) and the host (signing widget identity), each under a signing domain of its own. |
profiles.<name>.visitor_token_ttl |
widget (optional) | How long, in seconds, the visitor token the widget tag signs holds. Default 86400 (24 h), at most 7 days. A page left open longer needs a reload. |
profiles.<name>.webhook_url |
sync (optional) | Where AgentGraft posts tool calls. May also be set via ag.graft(webhook_url=...). Profile config wins if both are set. |
profiles.<name>.detailed_errors |
webhook view (optional) | True opts out of the generic error messages: the text of an exception your tool, hook or user loader raised goes back to AgentGraft, which shows it to the model. Off by default: the webhook answers with a generic message and the request id, and logs the exception. |
Pull api_key and webhook_secret from environment variables, never
from a checked-in settings file.
Decorator reference
import agentgraft as ag
@ag.user_loader
Resolves an opaque external id back to your user model. Called once per webhook request before any tool runs.
@ag.user_loader
def load_user(external_id: str) -> User:
return User.objects.get(pk=external_id.removeprefix("user:"))
The widget passes external ids prefixed with user: for authenticated
visitors and session: for anonymous visitors. Strip the prefix yourself
or branch on it. Optionally accept an is_anonymous: bool keyword:
@ag.user_loader
def load_user(external_id: str, *, is_anonymous: bool = False):
if is_anonymous:
return {"visitor_id": external_id.removeprefix("session:")}
return User.objects.get(pk=external_id.removeprefix("user:"))
Raise any exception (e.g. DoesNotExist) to fail the lookup — the
webhook view turns it into a 403. Only one @ag.user_loader per
profile.
@ag.tool
Defines a function the LLM can call. The function runs inside your host app, not on AgentGraft's servers.
@ag.tool
def search_assets(user: User, query: str, limit: int = 5) -> list[dict]:
"""Search the catalogue for assets matching the query."""
return list(user.assets.filter(name__icontains=query)[:limit].values())
Rules:
- The first parameter is always
userand is never sent to the LLM. - Every other parameter must have a Python type hint. The SDK builds a
JSON schema from those hints — no hint, no decoration. Modules using
from __future__ import annotationswork the same: the hints are evaluated, and one naming a type that isn't defined at module level fails at import. Only those hints are: theuserparameter and the return value may name types you import underif TYPE_CHECKING:.*args/**kwargsstay out of the schema. - The docstring becomes the description the LLM sees, or pass
description="...". - A parameter with a default is optional in the schema; without one,
it's required. An
Optionalone (str | None) without a default is optional too, and arrives asNonewhen the model leaves it out. - Tool names must be unique within a profile.
- Tools (like hooks and user loaders) are plain
deffunctions: the webhook calls them synchronously, soasync defis refused at import. - To tell the model why a call failed, raise
ag.WebhookError(status, "message"): its message reaches the model. Any other exception is logged on your side and answered with a generic message plus the request id (seedetailed_errorsabove).
Parameter descriptions
The LLM fills in tool arguments using the parameter name, its type, and — if provided — a natural-language description. Descriptions are one of the highest-leverage ways to improve tool call accuracy in a multi-agent system.
There are two ways to add them. Both produce the same result in the JSON schema the LLM receives. You can mix them freely in the same function.
Option 1 — Google-style Args: section (recommended default)
Write a standard Args: block in the docstring. The SDK extracts it
automatically at sync time — no extra imports required:
@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.
"""
...
The Args: section is stripped from the tool-level description before it
reaches the LLM — the model sees a clean summary in the tool description
and targeted guidance in each parameter's schema field.
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 knows the type from the signature.
Option 2 — ag.Param explicit override
Use ag.Param when you need to override a single parameter without
rewriting the full docstring, or when you want to attach examples:
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."""
...
Priority: 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.
Good descriptions answer: what is this value, where does it come from, and when should I omit it. They don't repeat type information already visible in the schema.
| Without description | With description |
|---|---|
dataset_id: int |
"Numeric ID returned by list_datasets" |
query: str |
"Free-text search across ticker and company name" |
since: str |
"ISO 8601 date string — only return events after this date" |
@ag.agent
Defines an agent — a system prompt with an allowed tool set and optional handoff targets.
@ag.agent(
entry=True,
tools=[search_assets, get_asset],
handoffs=["analyst"],
model="auto",
)
def concierge():
"""You are MyApp's concierge. Route the user to the right agent."""
The function body is never executed. Only the docstring matters — it becomes the agent's instructions. Kwargs:
| Param | Type | Default | Meaning |
|---|---|---|---|
entry |
bool | False |
The agent new widget conversations start on. Exactly one per profile: sync accepts none, but then only conversations your server starts with agent= can run. |
private |
bool | False |
Mark as the widget's private-chat agent. At most one per profile; cannot be entry or have handoffs / sub_agents. See below. |
unattended |
bool | False |
It answers with no person reading along (a bot or job your server runs). Cannot be private. See below. |
identity |
str | "" |
Who this agent is, in place of the graft's identity in its prompt. Blank keeps the graft's. See below. |
memory |
bool | True |
False: the agent neither reads nor writes the visitor's long-term memory. See below. |
tools |
list | [] |
Tool function references or string names. |
handoffs |
list | [] |
Agent function references or string names this one can hand off (transfer) to. |
sub_agents |
list | [] |
Agent function references or string names to call as tools (orchestrator pattern). |
model |
str | "auto" |
Any Cailos model codename — e.g. auto, auto:speed, auto:cost, claude-opus-4-7, gpt-5. Passed to Cailos verbatim; invalid values surface as Cailos errors. |
handoffs vs sub_agents — use handoffs when you want to transfer the conversation to another agent (the caller steps back). Use sub_agents when you want to delegate a task and get a result back — the calling agent stays in control and can use the result in its next step. Sub-agents run their own tool loop internally and return a string.
The agent a handoff reaches keeps the conversation: the visitor's next message starts with it, so give specialists a handoff back. A sub-agent is offered to the caller as a tool named after it, described by its own docstring; it sees only the text the caller passes it, not the conversation, and may make up to 50 model calls.
Private chat (private=True)
Mark one agent private=True and the widget shows a
ghost button that opens an incognito chat with it. AgentGraft saves
nothing from that chat: no conversation, no messages, no memory. The
widget keeps the transcript in the page and resends the recent turns
with each message (as many as fit in half of context_window_tokens,
up to 40), so reloading discards it. The agent sees the graft prompt,
the visitor's display name and the date, but no memory tools or stored
facts. Its spend still counts toward visitor_quota_usd. Tool calls
still reach your webhook, marked "private": true; a tool that writes
can check ag.current_call_is_private() and skip the write.
@ag.agent(private=True, tools=[search_docs])
def incognito():
"""You answer questions the visitor would rather not keep."""
Agents your server runs (unattended=True)
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 (see
"Running agents from your server"). 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 can't be private, since
a person reads the private chat.
@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 (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.
@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 (memory=False)
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.
@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 and the widget welcome screen.
ag.graft(
name="MyApp",
identity="You work inside MyApp's customer dashboard.",
product_context="MyApp is a portfolio analytics tool.",
voice="Be concise. Reach for examples over abstractions.",
scope="Only answer questions about the user's own portfolio.",
policies=[
ag.policy("agentgraft/no-hallucination"),
ag.policy("agentgraft/cite-sources"),
"Never give specific buy/sell advice.",
],
webhook_url="https://myapp.com/agentgraft/webhook/",
greeting="Ask me about your portfolio.",
example_prompts=[
"How is my portfolio performing this week?",
"Which positions are down the most?",
],
)
The five prompt fields (identity, product_context, voice, scope,
policies) get composed into every agent's system prompt at runtime.
The two widget fields (greeting, example_prompts) drive the empty
state visitors see before sending their first message — both fall back
to built-in defaults if blank.
policies accepts either a plain string OR a list mixing free-form
strings with ag.policy(...) references. References are resolved to
their full body text from the AgentGraft Policy Shop at sync time.
Runtime features are also configured via ag.graft() and applied at sync time. For the on/off switches (*_enabled), the server records when each was last turned on: syncing a switch that is already on keeps that time. The dashboard shows it, and the graft API returns it as <name>_at.
| Field | Type | Default | Description |
|---|---|---|---|
memory_enabled |
bool |
False |
Enable the long-term memory system. The Dreamer curates a persistent fact pool for each visitor in the background after their turns; agents with memory on get the built-in tools recall_memories and manage_memories. |
image_uploads_enabled |
bool |
False |
Let visitors drop, paste or pick images into a thread (up to 5 per message; a GIF is sent as a few still frames and counts as one). Offered only while the agent answering can see images; agents whose model can't get a text description of each image instead. On Safari the host page's CSP needs 'wasm-unsafe-eval' (or 'unsafe-eval') in script-src. |
voice_enabled |
bool |
False |
Turn on voice in the widget: replies read aloud, dictation, and opt-in hands-free listening. 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. Off: no voice controls, and the speech endpoints refuse. |
followups_enabled |
bool |
False |
End each reply with two or three suggested next questions the visitor can click. Adds one cheap model call per turn, made before the reply finishes. |
recap_enabled |
bool |
False |
Pre-generate a short "where you left off" recap after the conversation has been idle. Shown as a banner when the visitor reopens the thread; dismissed the moment they send their next message. |
recap_min_gap_minutes |
int |
30 |
Minutes of inactivity required before a recap is generated. Minimum: 30 (the sweep floor). |
recap_message_pairs |
int |
10 |
How many user + assistant message pairs to include in the recap window. |
recap_min_message_pairs |
int |
3 |
Minimum pairs that must exist before a recap is worth generating. Conversations shorter than this are skipped. |
context_window_tokens |
int |
32,000 |
Context window token limit for live thread profiling and context accounting in the widget (valid range: 4,096 to 512,000). |
max_message_chars |
int |
10,000 |
Maximum character length permitted per incoming user message (valid range: 1 to 10,000). |
visitor_quota_usd |
Decimal / float |
5.00 |
Rolling spend ceiling in USD per visitor across all conversations, including private chats and replies the visitor stopped early. |
visitor_quota_window_days |
int |
7 |
Rolling quota aggregation window in days (valid range: 1 to 365). |
The widget's look is set the same way, so it matches the app it sits in:
| Field | Type | Default | Description |
|---|---|---|---|
palette |
str |
"indigo" |
The widget's accent colour: buttons, links, and the face's eyes and juice. One of ag.PALETTES, below. Each has a dark and a light variant, so it follows the widget's theme. An unknown name fails at ag.graft(...), before any sync. |
visitor_palette_enabled |
bool |
False |
Let visitors pick their own palette in the widget's settings, over yours. Their pick stays in their browser; picking yours again puts them back on it. Off: everyone sees palette. |
| Palette | Dark | Light |
|---|---|---|
indigo (default) |
#5b67ff |
#1e2bd6 |
orchid |
#b94bc1 |
#84128c |
rose |
#db4887 |
#a3145b |
coral |
#e9543a |
#b92911 |
amber |
#e29122 |
#9e6414 |
jade |
#24b172 |
#137349 |
They're one family rather than a list of brand colours: set at the same perceived lightness, so any of them sits in the widget the way indigo does, and every one keeps its text readable in both themes.
Example:
from decimal import Decimal
ag.graft(
name="MyApp",
identity="You are MyApp's assistant.",
greeting="Ask me about your datasets.",
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 1 h of silence
palette="jade",
visitor_palette_enabled=True, # visitors may pick their own in settings
)
ag.policy(codename)
Reference a curated policy from the AgentGraft Policy Shop. Returns an opaque sentinel that the sync command resolves into the actual prompt text by fetching from the public catalogue.
ag.policy("agentgraft/mermaid-strict")
ag.policy("agentgraft/no-hallucination")
ag.policy("agentgraft/secrets-redaction")
Browse the catalogue at https://agentgraft.com/dashboard/policies/
or fetch the list yourself: GET /api/v1/policies/.
ag.reference(...) and ag.ref(type, id, label)
Let the assistant link to objects in your app as clickable chips. Declare
each type once (as many as you like), then return ag.ref(...) from the
tools that hand those objects back:
ag.reference(
"block",
label="Block",
description="A document in the user's knowledge base.",
url="/blocks/{id}", # optional fallback; path or https:// URL containing {id}
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("block", 42, "Q3 Plan") returns [Q3 Plan](ref:block/42). The
assistant pastes refs verbatim, and the widget renders them as chips. A
click dispatches a cancelable agentgraft:reference event on window:
window.addEventListener("agentgraft:reference", (event) => {
if (event.detail.type !== "block") return;
event.preventDefault(); // skip the url fallback
openBlock(event.detail.id);
});
If nothing calls preventDefault() and the type declares a url, the
widget navigates there. Types without a url render as buttons and do
nothing unless your handler acts on them. Ids may contain letters, digits
and . _ ~ @ : -, so integer pks, UUIDs and composite ids like
block@alice:k3f9 all pass through verbatim.
Refs are not checked against what your tools returned. Every ref:
link of a declared type renders as a clickable chip, including one the
model invented, repeated from text the visitor typed, or was steered into
writing by content a tool fetched. Treat the id a chip carries as
untrusted client input: check the current user may open that object
before you show it, exactly as you would for an id in a URL.
@ag.on_tool_call
Registers a hook that wraps every tool call a profile's webhook runs: audit trails, metrics, kill switches. See Tool-call hooks.
Multiple profiles
A single host app can declare multiple chat experiences in one config
file by passing profile= to the decorators:
@ag.tool(profile="public")
def what_is_myapp(user) -> str:
"""Return a one-paragraph pitch."""
return "MyApp is..."
@ag.agent(profile="public", entry=True, tools=[what_is_myapp])
def public_concierge():
"""You greet visitors on the marketing site."""
ag.graft(profile="public", name="MyApp Public", ...)
Each profile is an independent registry — a public-profile tool can never be called against an authenticated-profile user, and vice versa. Add the profile to settings:
AGENTGRAFT = {
"profiles": {
"default": {...},
"public": {...},
},
}
Sync individual profiles or all at once:
python manage.py agentgraft_sync # every declared profile (default)
python manage.py agentgraft_sync --profile public # one profile only
In templates, name the profile to render:
{% agentgraft_widget %} {# default #}
{% agentgraft_widget profile="public" %} {# named #}
Anonymous visitors
Anonymous visitors get persistent conversation history without a Django session. The template tag handles this automatically:
- Authenticated user → external id is
user:{user.pk},is_anonymous=False. The tag signs a visitor token for the id with the profile'swebhook_secret(see Visitor tokens). - Anonymous visitor → the tag writes the placeholder
data-user-id="browser:*"(ag.ANONYMOUS_VISITOR_ID) and signs the anonymous grant,ag.ANONYMOUS_VISITOR_GRANT, the same for every visitor. The widget picks a random id for the browser (browser:followed by 22 base64url characters) and sends it with the grant's signature. AgentGraft knows the visitor by asession:id derived from that one, which is what your loader gets, withis_anonymous=True. The widget keeps the browser id inlocalStoragefrom its first request (when the panel opens, including bydata-autoloador reopening as the visitor left it), so the same browser stays on the same conversation across reloads. Any page rendered for a logged-in user forgets it, on that origin only:localStorageis per origin, so a login onapp.example.comdoesn't clear whatwww.example.comkept.
The page is the same for every logged-out visitor: rendering the tag
creates no session and sets no cookie, so a crawler or uptime check costs
you nothing and the HTML is safe to cache for less than the token's
lifetime (24 h by default): a cached page whose token has expired turns
its visitors away. The widget sends the token
back as X-AgentGraft-User-HMAC on every API call; AgentGraft verifies it
and rejects forged identities. A valid grant vouches only for ids of the
widget's shape, never for a user: id. Anyone can start a new anonymous
conversation on a page that signs the grant, as anyone can by loading that
page, but no one can take over another visitor's: that takes the random id
kept in their browser, which AgentGraft never stores, shows or sends on.
Without the Django tag, write the same attributes yourself. For a
logged-out visitor, sign a token for the exact string
agentgraft:anonymous-visitor:v1 (ag.ANONYMOUS_VISITOR_GRANT), never the
placeholder id browser:* (ag.ANONYMOUS_VISITOR_ID):
signature = ag.compute_user_hmac(secret=webhook_secret, user_external_id=ag.ANONYMOUS_VISITOR_GRANT)
# Logged out: data-user-id="browser:*" data-user-hmac="{signature}"
# data-anonymous="true"
# Logged in: your own signed id, and data-anonymous="false" so the
# widget forgets the browser's logged-out id
Your @ag.user_loader receives both the external id and the
is_anonymous keyword — branch on it to return either a real User
row or a guest sentinel.
Visitor tokens
data-user-hmac (and the client's X-AgentGraft-User-HMAC) is a visitor
token that vouches for one id until it expires:
v2.<expiry>.<hex>
hex = HMAC-SHA256(webhook_secret, "agentgraft:visitor:v2\0" + user_id + "\0" + expiry)
expiry is unix seconds in decimal, \0 a NUL byte, and the id UTF-8.
ag.compute_user_hmac(secret=..., user_external_id=..., ttl_s=86400)
builds one (ttl_s up to 7 days); to write it in another language, follow
the format above. AgentGraft accepts a token up to 60 s past its expiry
(clock skew) and refuses one that expires more than 7 days ahead. The tag
signs a fresh one on every render, so a page reloaded keeps working, and
to cut a user off you stop signing for them: their last token stops
working when it expires.
AgentGraft still accepts the legacy bare HMAC-SHA256(webhook_secret, user_id) that SDKs before 0.18 sign, which never expires, while hosts
upgrade. Both are checked against the previous webhook secret too for 24
hours after a rotation.
Tool-call hooks
@ag.on_tool_call registers a hook that wraps every tool call a
profile's webhook runs. Use it for what applies to all your tools at
once: an audit trail, metrics, a kill switch, deduplicating retries.
Each tool stays a plain function.
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),
)
A hook gets the call and proceed. Calling proceed() runs the rest
of the chain (the next hook, and last the tool) and returns its result.
Whatever the hook returns is the call's result, so a hook can:
- let it run:
return proceed(), doing what it likes around it; - replace the result:
return {**proceed(), "checked": True}; - answer without running the tool: return without calling
proceed(); - refuse it:
raise ag.WebhookError(403, "search is disabled"). The status and message go back to AgentGraft, which shows the model the error (a 502, 503 or 504 makes it retry the call once). Any other exception from a hook, like one from a tool, is a 500.
@ag.on_tool_call
def kill_switch(call: ag.ToolCall, proceed):
"""Tools an operator has switched off answer 403, whatever the agent."""
if call.tool in settings.DISABLED_AGENT_TOOLS:
raise ag.WebhookError(403, f"{call.tool} is switched off")
return proceed()
What a hook sees — ag.ToolCall, a frozen dataclass:
| Field | |
|---|---|
tool |
The tool's registered name |
arguments |
The model's arguments, validated (pydantic-typed ones as instances). A read-only view: a hook cannot add, remove or replace an argument |
user |
What your @ag.user_loader returned |
user_external_id, is_anonymous |
Who the call is for, as on the wire |
private |
True for a call from the widget's private (incognito) chat |
agent |
The agent that made the call, by its name in your config ("researcher"). None from AgentGraft servers that predate it |
request_id |
The same on AgentGraft's retry of the call: an idempotency key |
profile |
The profile the call was dispatched against |
conversation_id |
The conversation whose turn made the call. None from the private chat, which isn't stored |
turn_key |
The turn_key you sent with that turn, so you know which of your turns each call is from. None for a turn sent without one |
When hooks run. Only for calls that reach a tool: the signature and
timestamp verified, the user loaded, the arguments checked against the
tool. A call refused before that (401, 403, 404, or 400 for bad
arguments) never reaches a hook. With several hooks, the first
registered is outermost. Hooks belong to a profile:
@ag.on_tool_call(profile="public"). They run in the webhook's
request, before and after the tool, so whatever they do adds to every
call's latency.
The call in progress. While a call runs, ag.current_tool_call()
returns it, to hooks and to the tool itself (and anything they call).
It is None outside a webhook call. ag.current_request_id() and
ag.current_call_is_private() are shorthands for two of its fields.
Testing a hook. A hook is a plain function, returned unchanged by
the decorator. Call it with a ToolCall and a proceed of your own:
def test_audited_logs_the_agent(db):
call = ag.ToolCall(
tool="search",
arguments={},
user=make_test_user(),
user_external_id="user:1",
is_anonymous=False,
private=False,
agent="researcher",
request_id="req_1",
profile="default",
)
assert audited(call, lambda: {"hits": 3}) == {"hits": 3}
assert AuditLog.objects.get().agent == "researcher"
agentgraft.testing.call_tool runs a tool alone, without the hooks.
manage.py agentgraft_sync
python manage.py agentgraft_sync # push every declared profile
python manage.py agentgraft_sync --profile X # push profile X only
python manage.py agentgraft_sync --dry-run # print the payload, don't send
python manage.py agentgraft_sync --retries 5 # retry up to 5 times on transient errors
--retries covers the policy fetches and the push itself: network
errors, 429 and 5xx are retried with back-off. The push is declarative,
so repeating it is safe. --dry-run needs no api_key or graft_id and
sends nothing; it only fetches ag.policy(...) references, from the public
Policy Shop at api_base.
What it does:
- Reads the named profile's settings. Refuses to run if
api_base,api_key, orgraft_idare missing. - Reads the registry populated at app startup. Refuses to run if it's empty (usually means the config module failed to import).
- Resolves any
ag.policy(...)references by fetching from the public Policy Shop endpoint. - Composes the resolved bodies + free-form strings into a single
policiestext block. - Builds the sync payload (tools, agents, graft metadata).
- POSTs to
{api_base}/api/v1/admin/grafts/{graft_id}/sync/withAuthorization: Bearer {api_key}. - Prints a summary of added / updated / removed tools and agents.
Sync is declarative: tools and agents that exist on the server but not in your local config are deleted. Push the entire registry, every time. The server applies it atomically — either every diff lands or none do.
The webhook view
Mounted by path("agentgraft/", include("agentgraft.django.urls")).
Exposes:
POST /agentgraft/webhook/— default profilePOST /agentgraft/webhook/<profile>/— named profile
The view:
- Verifies the
X-AgentGraft-Signature-V2HMAC against the profile'swebhook_secret. Bad or missing signature →401, and so is a request with only the legacyX-AgentGraft-Signature(see the wire contract). - Parses the JSON body. Bad JSON →
400. A signedtimestampthat is missing, or more than 5 minutes from the host clock →401(replay protection). - Looks up the tool by name. Unknown tool →
404. - Calls your
user_loader. Any exception →403. - Checks the LLM-supplied arguments fit the tool. Mismatch →
400. - Runs the call through your tool-call hooks, then
the tool function with the user + arguments. A
WebhookErrorraised by either answers with its own status and message; other exceptions →500. - Returns
{"result": <whatever the tool returned>}as JSON.
AgentGraft shows the model the error message of a failed call, so an
exception from your tool, hook or user loader is logged on your side
(agentgraft.webhook logger, with its traceback) and answered with
"Tool 'x' failed (request req_…)." / "User lookup failed (request req_…).": search your logs for the request id. Set the profile's
detailed_errors to True to opt out and send the exception text
instead.
The view is csrf_exempt and require_POST. You write none of this —
just register your tools and a user_loader.
The wire contract
For debugging what AgentGraft sends to your webhook.
Request body:
{
"tool": "list_datasets",
"arguments": { "limit": 5 },
"user_external_id": "user:42",
"is_anonymous": false,
"private": false,
"agent": "researcher",
"conversation_id": "6f1c2a90-...",
"turn_key": null,
"request_id": "req_018f3a...",
"timestamp": 1712345678
}
is_anonymous is true for ids in the session: namespace. The SDK
also derives it from the prefix, so it works against older servers.
timestamp and request_id are inside the signed body, so they can't
be altered or stripped; a body without a timestamp is refused.
AgentGraft waits up to 120 s for each call and retries it once on a
connection failure or a 502/503/504, resending the same body: tools that
write can call ag.current_request_id() and use it as an idempotency key.
It does not retry a call that timed out waiting for your reply, since your
tool may still be running.
private is true when the call came from the widget's incognito
chat, which AgentGraft does not store. ag.current_call_is_private()
returns that flag inside the tool so a write can skip itself. Older
servers omit the field; the SDK treats that as false.
agent names the agent that made the call, as declared in your
config; hooks get it as ToolCall.agent. Older servers omit it
(None).
conversation_id is the conversation whose turn made the call (null
from the private chat), and turn_key the key you sent with that turn,
or null; hooks get them as ToolCall.conversation_id and
ToolCall.turn_key. Older servers omit both.
Headers:
Content-Type: application/json
X-AgentGraft-Signature-V2: <hex HMAC-SHA256(webhook_secret, "agentgraft:webhook:v2\0" + raw body)>
X-AgentGraft-Signature: <hex HMAC-SHA256(webhook_secret, raw body)> (legacy)
X-AgentGraft-Graft: <graft id>
\0 is a NUL byte. The SDK verifies X-AgentGraft-Signature-V2 only
(ag.compute_webhook_signature(secret=..., body=...) computes it).
AgentGraft also sends the legacy X-AgentGraft-Signature for hosts on
SDKs before 0.18, but this SDK refuses a request that carries only that
one: it is the same construction those SDKs signed visitor ids with, so a
host that signed an id an attacker chose would have handed them a valid
signature for a forged body. Verifying the webhook in another language,
check the V2 header.
Success response (200):
{ "result": <whatever the tool returned> }
Error responses: {"error": "<message>"} with one of:
| Code | Meaning |
|---|---|
| 400 | Malformed JSON, missing tool, bad arguments |
| 401 | Invalid HMAC, missing signature, or stale timestamp |
| 403 | user_loader raised |
| 404 | Tool name not in the registry |
| 500 | Tool function or a hook raised, or webhook secret not configured |
A tool-call hook (or a tool) can also answer with a status of its own
by raising ag.WebhookError(status, message).
Migration import API
Migrating from another chat platform, or rolling your own history into a fresh graft? Backfill end users + conversations + messages with a single POST so the Dreamer can extract long-term memory and the recall agent can retrieve it. Without this, every migrated visitor starts "cold" — empty fact pool, no history — and their experience regresses.
Endpoint — POST /api/v1/admin/grafts/{graft_id}/import/
Auth — your existing graft API key, same Authorization: Bearer sk_live_…
header used by agentgraft_sync.
Request body
{
"dry_run": false,
"users": [
{
"external_id": "user:42",
"display_name": "Optional display name",
"conversations": [
{
"title": "Optional",
"messages": [
{"role": "user", "content": "hi", "created_at": "2026-01-15T10:00:00Z"},
{"role": "assistant", "content": "hello", "created_at": "2026-01-15T10:00:05Z"}
]
}
]
}
]
}
Contract
- Purely additive. If an
EndUserwith thisexternal_idalready exists in the graft, that row is reused and the supplied conversations are appended under it (users_mergedin the summary); itsdisplay_nameis left as it is. Conversations are never deduped, so re-sending a payload imports its conversations twice. - Your
external_idmust be the id your widget signs. The{% agentgraft_widget %}tag signsuser:followed by the user's primary key, so a user whose pk is 42 is imported asuser:42; a visitor your server reaches throughClientis theuser_idyou pass it. We store and match it verbatim, never normalising it: if it differs by one character, the imported history belongs to a visitor who never signs in. Logged-out visitors' ids are derived from their browsers and can't be imported. - Required fields.
display_nameandtitleare optional.external_id,conversations(which may be empty),messages,role,content(which may be blank) andcreated_atare required. - Original timestamps are preserved on every message, so the Dreamer reads the history in real chronological order.
- Token counts are recomputed from message content for consistency;
cost_usdis always0for imported messages (we didn't serve them, we don't bill for them). dry_run: truevalidates + reports counts without writing anything and without enqueueing any background jobs.
Role mapping (silent)
Source systems use all kinds of role names. These are silently mapped to the canonical AgentGraft roles at import time:
| Incoming role | Stored as |
|---|---|
user, human, customer, end_user, enduser |
user |
assistant, bot, ai, gpt, model |
assistant |
tool, function |
tool |
tool and function messages are recognised and dropped, each with a
warning, and counted in messages_dropped_tool: the tool call they
answered can't be imported, and without it the model would refuse the
conversation. So an "Export my data" file imports as it is.
Anything else is rejected as a validation error. system is
explicitly not mapped — it's an internal orchestrator role and
would let a migration payload inject instructions into a visitor's
memory.
Alternation enforcement
Imported history must follow user → assistant alternation (tool
messages between them are fine). If the source system lost an
assistant reply and has two consecutive user messages — or a user
message with no response at all — the stranded user message is
dropped with a warning instead of creating a broken conversation.
If a conversation becomes empty after this cleaning, it's skipped with a warning. Empty conversations are never created.
Response
{
"dry_run": false,
"summary": {
"users_created": 12,
"users_merged": 1,
"users_failed": 0,
"conversations_created": 40,
"conversations_skipped_empty": 3,
"messages_created": 812,
"messages_dropped_orphan_user": 5,
"messages_dropped_tool": 0
},
"warnings": [
{"user_external_id": "u-7", "conversation_index": 0, "reason": "conversation empty after cleaning, skipped"},
{"user_external_id": "u-7", "conversation_index": 1, "message_index": 4,
"reason": "orphan user message dropped (no assistant response)"}
],
"errors": [
{"user_external_id": "u-99", "reason": "unknown role 'overlord' at conversations[0].messages[2]"}
]
}
users_merged counts end-users whose (graft, external_id) row
already existed: the row is reused and the supplied conversations
are appended under it. Conversations themselves are never deduped,
so avoid re-sending conversations you've already imported.
Per-user errors don't abort the whole batch — each user's work is
wrapped in a savepoint, so a message with a role we can't map rolls back
just that user. Siblings succeed. A payload whose shape is wrong (a
missing or unreadable created_at, a field over its limit) is refused
whole with a 400 naming the field, and nothing is written.
What happens after import
For grafts with memory_enabled=True, the Dreamer is automatically
scheduled for every newly-created conversation as soon as the import
commits. It reads the conversation only when the graft's entry agent has
memory on, as for any conversation that agent answers, and the Reflector
may then queue questions to ask the visitor later, as after live chat.
Embeddings are
scheduled for every imported user and assistant message with content,
regardless of the memory toggle: message search uses them, and on a
graft with memory on the recall agent searches them too once the visitor
has a fact. All of this runs asynchronously via Celery — the API
response returns as soon as the rows are written, and memory builds up
in the background. Imported conversations join the auto-router's
candidates once the visitor sends a message in them.
Limits
There are no rate limits, but each field has one: external_id up to
255 characters, display_name up to 60, a conversation title up to
255, and users must hold at least one user. Message content is not
held to the graft's max_message_chars. The request is synchronous, so
keep batches reasonable (hundreds of users, thousands of messages) and
chunk bigger imports client-side. Before retrying a chunk whose response
you never saw, check whether it landed: a chunk that committed imports
its conversations twice if sent again.
Type-hint → JSON schema
| Python annotation | JSON schema |
|---|---|
str |
{"type": "string"} |
int |
{"type": "integer"} |
float / Decimal |
{"type": "number"} |
bool |
{"type": "boolean"} |
list[T] / Sequence[T] |
{"type": "array", "items": <T>} |
dict / dict[K, V] / Mapping |
{"type": "object"} |
datetime / date / time / UUID |
{"type": "string", "format": "date-time"} (date, time, uuid) |
Optional[T] / T | None |
<T>, removed from required |
Literal["a", "b"] |
{"type": "string", "enum": ["a", "b"]} |
Literal[True, False] |
{"type": "boolean", "enum": [true, false]} |
Enum subclass |
{"type": "string", "enum": ["val1", "val2", ...]} |
Annotated[T, ag.Param("…")] |
<T schema> + "description": "…" |
pydantic model (or list[Model]) |
the model's schema, $refs inlined |
Any / object |
{} (any JSON value) |
A parameter with a default value is removed from required even if
its annotation isn't Optional. Missing type hints are a hard error
at decoration time — fail loud, not later in production. A type with no
JSON Schema form (bytes, timedelta, your own class, ...) becomes {}
with a warning naming the tool and parameter: annotate it Any to
accept any JSON value on purpose.
Only pydantic models are converted on the way in. Every other argument
reaches your function as the JSON value the model sent: a date as its
ISO 8601 string, a UUID as a string.
A pydantic-typed argument reaches your function as a validated model
instance (a list of them for list[Model], and None for an Optional
one sent as null). If the model sends one that doesn't validate, the
call fails with a 400 saying where and what is wrong (stops[2].dwell_ms: Input should be less than or equal to 30000), and the model can retry
with a corrected call:
from pydantic import BaseModel, Field
class Stop(BaseModel):
target: str
dwell_ms: int = Field(default=4000, ge=1000, le=30000)
@ag.tool
def set_tour(user, stops: list[Stop]) -> dict:
"""Replace the tour of the user's open space."""
... # stops is a list[Stop]
Keep tool models to keywords every provider accepts: prefer ge/le
over gt/lt, and defaults over Optional fields. Recursive models
(a model that contains itself) can't be inlined, so they aren't supported:
a tool taking one fails at import, naming the model.
Testing
Tools are plain Python functions. Call them directly with a stub user:
def test_list_datasets():
user = make_test_user()
result = list_datasets(user)
assert all("id" in row for row in result)
For richer test coverage, use the agentgraft.testing module. It provides
two utilities and a pytest fixture:
# conftest.py — enable the fixture project-wide
pytest_plugins = ["agentgraft.testing"]
from agentgraft.testing import call_tool, tool_schema
def test_get_order_calls_tool(db, ag_reset):
user = make_test_user()
# call_tool injects user as the first argument, just like the webhook does
result = call_tool(get_order, user, order_id="abc123")
assert result["id"] == "abc123"
def test_get_order_schema():
schema = tool_schema(get_order)
assert "order_id" in schema["required"]
assert schema["properties"]["order_id"]["type"] == "string"
call_tool(fn_or_name, user, **kwargs) — call a registered tool by reference
or by string name, injecting user as the first argument. Arguments typed as
pydantic models are validated into instances first, as the webhook does. The
tool runs alone, without the profile's tool-call hooks.
tool_schema(fn_or_name) — return the JSON schema dict the SDK would push at
sync time. Use it to assert that parameter descriptions and types are exactly
right before they reach production.
ag_reset fixture — resets the registry before and after each test, preventing
decorator-side-effect registrations from leaking between test cases.
Without Django
The framework-agnostic core (registry, decorators, schema generation,
webhook handler) is importable on its own. The Django adapter is a
thin wrapper around agentgraft.handle_webhook, which you can call
from any framework:
import os
from agentgraft import handle_webhook, WebhookError
def my_flask_view():
try:
result = handle_webhook(
body=request.get_data(),
signature=request.headers.get("X-AgentGraft-Signature-V2", ""),
webhook_secret=os.environ["AGENTGRAFT_WEBHOOK_SECRET"],
profile="default",
)
except WebhookError as exc:
return {"error": exc.message}, exc.status_code
return result, 200
signature is the X-AgentGraft-Signature-V2 header (ag.SIGNATURE_HEADER);
an adapter written for SDKs before 0.18 passes X-AgentGraft-Signature,
and every call is then refused with a 401 naming the header to pass.
webhook_secret is required: it is what the signature is checked
against. Pass detailed_errors=True to opt out of the generic error
messages and send exception text back.
The same pattern works for FastAPI, Starlette, Bottle, raw WSGI. Native adapters for other frameworks are not yet shipped.
Working from a source checkout
agentgraft.__version__ is sourced from installed package metadata via
importlib.metadata. If you're running the SDK from a source checkout
that hasn't been pip install-ed, the lookup falls through to a
sentinel:
>>> import agentgraft
>>> agentgraft.__version__
'0.0.0+local'
This is by design — there's no dist-info directory to read from. Run
pip install -e sdk/ (or your equivalent) to populate the metadata
and pick up the real version string.
License
MIT. See LICENSE for the full text.
Metadata
Release files for agentgraft 0.20.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| agentgraft-0.20.0.tar.gz | 192.3 kB | Without provenance | Details for agentgraft-0.20.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| agentgraft-0.20.0-py3-none-any.whl | Python 3 | none | any | Details for agentgraft-0.20.0-py3-none-any.whl |
Total release size: 290.1 kB
Release files / agentgraft-0.20.0.tar.gz
| Download URL | agentgraft-0.20.0.tar.gz |
|---|---|
| Size | 192.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
47d2a6117a9ada9cbbc71e479d2d5d1eb53b9f3597b64354bae391fade8925c0
|
|
BLAKE2b-256 checksum How to use checksums |
afa08222d6cf5b83479871b948b9bcefaad7676dbe30c41a4c4387f85f5dbab7
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.14.0
|
Release files / agentgraft-0.20.0-py3-none-any.whl
| Download URL | agentgraft-0.20.0-py3-none-any.whl |
|---|---|
| Size | 97.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
e5ba73b9642f356027aedcdca1a2ffc7b692904c6f6e2bad31ce0f5adb1e5c0f
|
|
BLAKE2b-256 checksum How to use checksums |
623958a30190ecbf5155c344a9629ba94af06d8a79df96d013eb92c2b426922b
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.14.0
|
Security for agentgraft 0.20.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.
No provenance found
None of the files in this release were uploaded with provenance metadata.
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.