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:
# 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).
- Timeouts.
Client(timeout=120) is the socket timeout of each
request. With that default, send_message and chat wait up to 630 s
instead, the longest a turn can hold its conversation: a non-streaming
turn replies only once it is over. A timeout you pass applies to
turns too, and timeout=None waits as long as it takes. A turn that
times out may still be running; its reply lands in get_messages, and
resending meanwhile gets a 409. Prefer stream_chat for anything
interactive.
- Streaming is lazy.
stream_chat sends nothing until you start
iterating, and its errors (auth, HTTP status, network) are raised from
the loop, not the call. Keep the loop inside your try.
- Retries. Reads, deletes and the sync push are retried on network
errors, 429 and 5xx with jittered exponential back-off (
max_retries=3).
A Retry-After in 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_name and visitor_timezone
travel in HTTP headers, which carry Latin-1 text only. A user_id
outside that (or with line breaks) raises ValueError before anything
is sent: use an ASCII id such as the primary key. A visitor_name
outside 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_base is plain http:// to anything but this machine. Redirects
are never followed: a 3xx reply raises an APIError naming where it
pointed, so set api_base to the address the API answers on.
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 and spend_as need
api_key, which the client sends in X-AgentGraft-Server-Key with
those calls only. Without it the client raises ValueError before
sending anything. The server refuses them from a page (403) and
refuses a wrong key (401).
agent starts a conversation that create_conversation or chat
makes on any of the graft's agents but the private one. It answers
every turn until it hands off. A conversation chat routes to or is
given keeps its own agent.
instructions go 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.
spend_as points 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 its 429, 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_usage reads the allowance a visitor spends from and what
each id in actors spent 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_data deletes 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.
- Mark the agents your server runs
unattended=True (see @ag.agent),
give a bot an identity of its own, and set memory=False on 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.
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 |
Bearer token for /api/v1/admin/grafts/{id}/sync/. Shown once at graft creation. |
profiles.<name>.public_key |
widget |
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 |
HMAC signing secret used by both AgentGraft (signing tool dispatches) and the host (signing widget identity). |
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