Python client SDK for the xAgent HTTP v1 API. Lets a SaaS app authenticate as a user, mint AI agents from templates, and trigger them — all in a handful of lines.
Status: early access. Optional
xagent_sdk.cloud.WorkspaceClient(hosted workspace surface) selects a hosted region. Breaking change vs 0.1.0: the SDK exposes two clients (UserClientfor a personal key,AgentClientfor an agent key) instead of a single class, and/v1/mereturns a user principal instead of an agent identity. See Migration from 0.1.0 below.
Pin to a release tag — do not install from main. Replace vX.Y.Z
with a tag from the tags page:
pip install "xagent-sdk @ git+https://github.com/xorbitsai/xagent-sdk@vX.Y.Z#subdirectory=python"The Python client lives under python/ in the
xagent-sdk monorepo; the
#subdirectory=python fragment tells pip where to find pyproject.toml.
Python 3.11+ required.
Set credentials via environment (recommended) or pass them to the constructors:
# personal key — for UserClient (identity, templates, agents, skills, MCP connectors, models, and tasks on any agent you can see)
export XAGENT_PERSONAL_KEY="xag_personal_..."
# runtime key — for AgentClient (chat tasks against a specific agent)
export XAGENT_API_KEY="xag_..."
# shared base URL
export XAGENT_BASE_URL="https://your-xagent.example"The two env vars are intentionally distinct so you can hold both keys in the same process without one overriding the other.
0.2.0 is a breaking release. Two changes affect existing 0.1.0 code:
XAgentClientwas renamed toAgentClient. The class is identical otherwise — only the name and import path changed.client.me()no longer exists onAgentClient. Identity moved toUserClient.me()and the response shape changed too (UserPrincipalwithuser_id/username/email/principal_type/key_prefix, replacingMeResponsewithagent_id/agent_name). Listing your agents now goes throughUserClient.agents.list()instead.
Minimal 0.1.0 → 0.2.0 sed pass (assuming your code already had
XAGENT_API_KEY set):
# Rename the runtime client wherever it appears.
sed -i '' 's/XAgentClient/AgentClient/g' your_app.py
# Delete imports of the removed MeResponse class; if you used the
# value, you will need to migrate to UserClient.me() returning
# UserPrincipal (see Example 1).
sed -i '' '/MeResponse/d' your_app.pyImporting the old names from 0.2.0 raises ImportError immediately
(not a runtime AttributeError halfway through), so missed
callsites are surfaced at startup.
The happy path is two steps: use a personal key to mint or look up an agent, then use that agent's runtime key to run tasks against it.
from xagent_sdk import AgentClient, UserClient
# Step 1: management — pick a template and create an agent. The
# response carries a one-time runtime key.
with UserClient() as user: # reads env vars
new_agent = user.agents.create_from_template(
"support-ai-chatbot-agent",
overrides={"name": "HR Leave Assistant"},
)
runtime_key = new_agent.runtime_full_key # store in a vault
agent_id = new_agent.agent_id
# Step 2: runtime — call the agent.
with AgentClient(api_key=runtime_key) as agent:
result = agent.tasks.run(
agent_id=agent_id,
message="How much sick leave do I have left?",
)
print(result.output)The runtime key is the only thing the SDK exposes a copy of; the
backend stores a bcrypt hash and cannot return the secret again.
Persist it to a secret manager before discarding the
AgentCreateResult.
- User: a human (identified by personal key) who owns agents
inside their workspace.
UserClient.me()returns this user as aUserPrincipal. - Personal key:
xag_personal_<prefix>_<secret>— the user's long-lived credential, held byUserClient. Authorizes/v1/me,/v1/templates*,/v1/agents*,/v1/skills*,/v1/mcp-servers*,/v1/modelsand the/v1/chat/tasks*task endpoints (user.tasks). A task started this way runs as you, not as the agent's owner, and every personal key of yours sees the tasks any of them created, until the task's agent is deleted. - Agent: a server-side template instance (system prompt + tools +
model config). Created via
UserClient.agents.create()orUserClient.agents.create_from_template(). - Agent runtime key:
xag_<prefix>_<secret>— belongs to one agent, which can hold several at once; authorizes only/v1/chat/tasks*. Returned once byagents.create*(whengenerate_runtime_key=True), byagents.rotate_key()(which revokes the agent's other keys) or byagents.add_key()(which leaves them working). - Template: a server-managed preset (Content Generator, Analyzer,
Q&A, Assistant, ...). Returned by
UserClient.templates.list(); the per-template detail (TemplateDetail.agent_config) is the merge target forcreate_from_templateoverrides. - Task: one conversation session against an agent. Created with the first user message; subsequent turns append to the same task.
- Step: one entry on the agent's public timeline. Four types —
message,thinking,tool_call,agent_delegation.
from xagent_sdk import UserClient
with UserClient() as user:
me = user.me()
print(f"user_id={me.user_id} username={me.username} email={me.email}")Each call hits the backend; cache the value locally if you need it more than once.
from xagent_sdk import AgentClient, UserClient
with UserClient() as user:
templates = user.templates.list()
print([t.template_id for t in templates])
# template ids are backend-defined, e.g.
# ['support-ai-chatbot-agent', 'sales-inbound-agent', ...]
detail = user.templates.get("support-ai-chatbot-agent")
# detail.agent_config is the merge target the backend uses below
created = user.agents.create_from_template(
"support-ai-chatbot-agent",
overrides={"name": "Policy Bot"},
)
print(created.agent_id, created.runtime_key_prefix)
with AgentClient(api_key=created.runtime_full_key) as agent:
result = agent.tasks.run(
agent_id=created.agent_id,
message="Summarize today's PTO policy.",
)
print(result.output)with UserClient() as user:
for agent in user.agents.list():
print(agent.agent_id, agent.name, agent.status)Use this when a runtime key was leaked, when scheduled rotation fires, or when the SDK consumer has lost the value (the SDK never caches the secret — only the backend has the hash).
with UserClient() as user:
rotated = user.agents.rotate_key(agent_id=42)
print("save:", rotated.full_key)
# Every previous runtime key is now revoked; any AgentClient still using one
# will start raising InvalidAPIKey on its next request.rotate_key() revokes every key of the agent at once. To move your services
to a new key while the old one keeps working, add the new key, deploy it, then
revoke only the old one:
from xagent_sdk import UserClient
with UserClient() as user:
agent_id = 42
old_prefix = "Ab12Cd" # the key_prefix of the runtime key in use today
# 1. Add a new key. Every existing key keeps working.
new = user.agents.add_key(agent_id, label="prod-2026-12-03-a1b2")
save_to_secret_manager(new.full_key) # full_key is shown only once
# 2. Deploy new.full_key to every service that calls this agent.
# 3. Confirm the switch: the new key is used, the old one is not.
for k in user.agents.list_keys(agent_id):
print(k.key_id, k.label, k.key_prefix, k.last_used_at)
# 4. Revoke only the old key.
old = next(k for k in user.agents.list_keys(agent_id) if k.key_prefix == old_prefix)
user.agents.revoke_key(agent_id, old.key_id)Things to know:
- Do not call
rotate_key()in this flow. It revokes all of the agent's keys, including the one you just added. - Give each
add_key()call, retries included, a label that no key of this agent has used, by you or anyone else (for example one that ends in a random suffix). If the call times out or raisesInternalError(HTTP 500),XAgentTransportErrororMalformedResponse, the key may still have been created, and the server can still be saving it after your connection ends. Wait a few seconds, list the keys and revoke any key that has the label of the failed call and whosekey_prefixis not one you hold. Then retry with a new label, and after the retry succeeds check once more and revoke any key that has the label of a failed call and whosekey_prefixis not one you hold. - The server does not require labels to be unique. If the failed call had no
label, or its label may be in use elsewhere, do not revoke by label: revoke a
key only when you know that nobody holds its
key_prefix.
from xagent_sdk import AgentClient
with AgentClient() as agent:
task = agent.tasks.create(
agent_id=42, message="Reply with 'first'."
)
info = agent.tasks.wait(task.task_id)
print(info.output) # 'first'
agent.tasks.append(
task.task_id, agent_id=42, message="Now reply with 'second'."
)
info = agent.tasks.wait(task.task_id)
print(info.output) # 'second'append() returns immediately with status='pending' when the server
queues the turn for its dispatcher, or status='running' when it runs
the turn in-process.
Until a queued turn starts, get() reports the task as PENDING with
output, error and completed_at set to None, even when the previous
turn had finished as COMPLETED or FAILED; once the turn starts it
reports RUNNING. A server older than v0.8.5 instead keeps reporting the
previous turn until the new one starts. With such a server, read
completed_at from get() before appending; once get() shows a
different value, the server is on the new turn and wait() returns its
result.
If you race two appends, the loser gets TaskBusy (409). Wait for the
winning turn to finish and send again; another caller can win the next
race too, so catch TaskBusy and retry after a pause:
import time
from xagent_sdk import TaskBusy
for attempt in range(3):
try:
agent.tasks.append(task.task_id, agent_id=42, message="...")
break
except TaskBusy:
if attempt == 2:
raise
agent.tasks.wait(task.task_id)
time.sleep(1)append() raises InteractionResponseRequired if the task is
WAITING_FOR_USER -- answer its pending question with reply()
instead (see Example 7 below).
An agent can pause a task mid-run to ask the caller something. wait()
and run() return with status=WAITING_FOR_USER when that happens;
read the question off pending_interaction and answer with reply()
(not append()):
from xagent_sdk import AgentClient, TaskStatus
with AgentClient() as agent:
result = agent.tasks.run(agent_id=42, message="Book me a flight")
if result.status is TaskStatus.WAITING_FOR_USER:
pending = result.info.pending_interaction
if pending is not None:
print(pending.question) # "Where are you flying to?"
print(pending.interactions) # structured controls, or None
# pending can still be None here: the task can pause in
# WAITING_FOR_USER without ever recording a question turn.
# reply() is valid either way.
agent.tasks.reply(
result.info.task_id, agent_id=42, message="To Tokyo, next Friday"
)
info = agent.tasks.wait(result.info.task_id)reply() resumes the task's paused execution -- the same server-side
run continues rather than a new one starting, unlike append() -- so
the run_id on the AppendResult it returns is the run the task already
had, not a new one. Waiting with it as expected_run_id rules out another
run, not a new question from this run. It is also not idempotent -- the SDK
sends no request-level idempotency key, so a client-side timeout does
not tell you whether the answer was delivered. If a call raises
XAgentTransportError (network/timeout below the HTTP layer), call
get() first and only retry if status is still WAITING_FOR_USER.
The retry can still raise TaskBusy while the server is still handling
an earlier answer -- yours or another caller's. That does not mean your
answer was applied: the earlier one can still be rejected. Wait, call
get() again and repeat this check:
from xagent_sdk import TaskBusy, XAgentTransportError
task_id = result.info.task_id
try:
agent.tasks.reply(task_id, agent_id=42, message="To Tokyo, next Friday")
except XAgentTransportError:
info = agent.tasks.get(task_id)
if info.status is TaskStatus.WAITING_FOR_USER:
try:
agent.tasks.reply(task_id, agent_id=42, message="To Tokyo, next Friday")
except TaskBusy:
# an earlier answer is still being handled and may still be
# rejected; check get() again later
passEven that check is not a full guarantee: the first reply may have
already gone through, and the agent may have immediately asked a new
question -- which also shows up as WAITING_FOR_USER. If
pending_interaction is not None, comparing its question against
the one you just answered rules out most of these cases, but not a
follow-up question that happens to repeat the same text, and
pending_interaction can itself be None -- so "compare the question"
is a partial mitigation, not a guarantee.
All SDK exceptions inherit from XAgentError and carry code,
message, http_status, details, and retry_after. Server-mapped codes:
| Exception | HTTP | Server code |
|---|---|---|
InvalidAPIKey |
401 | invalid_api_key |
AgentNotFound |
404 | agent_not_found |
TaskNotFound |
404 | task_not_found |
TemplateNotFound |
404 | template_not_found |
APIKeyNotFound |
404 | api_key_not_found -- raised by agents.revoke_key() when the agent has no runtime key with that id |
SkillNotFound |
404 | skill_not_found -- raised by skills.get(), skills.update() and skills.delete() |
ConnectorNotFound |
404 | connector_not_found -- raised by mcp_servers methods that take a server_id |
TransportNotSupported |
400 | transport_not_supported -- raised by mcp_servers.list_tools() for a connector whose transport is not streamable_http or sse; also raised by mcp_servers.create() and update() when the transport they are given is not one of those, and by update() when the connector's stored transport is not |
ConnectorUnavailable |
409 | connector_unavailable -- raised by mcp_servers.list_tools(); details["reason"] says why (team_shared, disabled, unsupported, client_rejected, unknown, or another lowercase reason string) |
McpOAuthAuthorizationFailed |
409 | mcp_oauth_authorization_failed -- raised by mcp_servers.list_tools() when the connector's OAuth authorization is missing or no longer works; it can only be fixed in the web app; details["reason"] says what is wrong |
ConnectorNameConflict |
409 | connector_name_conflict -- raised by mcp_servers.create() and update() when the name is already in use (names are unique across all users); details["connector_id"] is present only when the name is taken by one of your own connectors: after a timed-out create() it can be the connector that attempt made or one that existed before, so check it with get(), and after a rename in update() it is your other connector with that name |
ConnectorNotEditable |
409 | connector_not_editable -- raised by mcp_servers.update() and delete(); details["reason"] is catalog (an app connection from the catalog, changed only in the web app), managed_elsewhere (another account manages its OAuth connection), authorized_by_others (other accounts hold authorizations that changing url, auth.issuer or auth.resource_metadata_url would keep; make that change in the web app) or unknown |
ConnectorForbidden |
403 | connector_forbidden -- raised by mcp_servers.update(), delete() and set_enabled(), and by create() when the server refuses you a new connector; details["reason"] is team_shared (you see the connector only through your team, so it is read-only) or not_permitted (for example deleting a team-owned connector without being a team administrator) |
ConnectorNotShared |
400 | connector_not_shared -- raised by agents.replace_connectors() when the agent belongs to a team and the team cannot use the new selection; the team's deployment decides, and it checks the whole new list, so details["connectors"] (a list of {"name", "reason"}) can name connectors you did not send; reason is not_shared, disabled or unresolved today, treat any other string as not_shared; name can be an empty string; nothing was written |
ModelNotAssignable |
400 | model_not_assignable -- raised by agents.update() when a model slot it changes cannot take the requested model; nothing is written; details["models"] lists each refused slot, in slot order, as {"slot", "id", "reason"} (id is the requested model's id), plus owner_user_id when reason is owner_cannot_use; reason is unavailable, not_llm or owner_cannot_use (treat any other string as unavailable), and a slot sent with the model it already stores is never listed |
AgentToolsUnconfigured |
409 | agent_tools_unconfigured -- raised by agents.replace_connectors() when the agent uses the default tool set and has no selection of its own; choose its tools in the web app first; get_connectors() never raises it |
ConnectorToolsUnavailable |
502 | connector_tools_unavailable -- raised by mcp_servers.list_tools() when no tools were loaded; details["reason"] and details["failures"] (a list of {"phase", "attempts"}) say what failed |
TaskBusy |
409 | task_busy |
TaskNotCancellable |
409 | task_not_cancellable -- raised by cancel() when the task already ended without being cancelled, or another turn replaced the one the cancel was aimed at; do not retry |
SkillAlreadyExists |
409 | skill_already_exists -- raised by skills.create() / skills.upload() |
InteractionResponseRequired |
409 | interaction_response_required -- raised by append() on a WAITING_FOR_USER task; use reply() instead |
NoPendingInteraction |
409 | no_pending_interaction -- raised by reply() when the task is not WAITING_FOR_USER |
InteractionNotResumable |
409 | interaction_not_resumable -- raised by reply() when the task's execution state could not be restored; do not retry |
InvalidInput |
400 / 413 / 422 | invalid_input |
RateLimited |
429 | rate_limited -- also raised by mcp_servers.list_tools() when your account already has two listings in progress on that server process, or no free slot turns up in time; retry_after is the suggested wait in seconds |
InternalError |
500 | internal_error |
TemporarilyUnavailable |
503 | temporarily_unavailable -- raised by reply() on a transient read failure; safe to retry |
A 404 without the V1 error envelope (the framework's own
{"detail": "Not Found"}) surfaces as InternalError with
http_status=404 and the raw body as message. Names that cannot
address a skill are rejected locally with ValueError before any
request, so this 404 means the server has no such route -- typically a
server older than this SDK. It is distinguishable from SkillNotFound
by exception type.
details is the details object of the server's error response, as
sent, or None when there is none. Its keys depend on the code and may
grow between server versions, and it can be {}, which is not the same
as None. For example, when reply() fails because the server did not
take the answer, details["accepted"] is False; when the server took
it but could not tell the outcome (InternalError, code
reply_outcome_unknown), it is True:
from xagent_sdk import InternalError, TaskBusy
try:
user.tasks.reply(task_id, agent_id=agent_id, message="Yes, go ahead")
except TaskBusy as e:
if e.details and e.details.get("accepted") is False:
... # the server did not take this reply; it is safe to send it again
else:
... # the task is busy; try again later
except InternalError as e:
if e.details and e.details.get("accepted") is True:
... # the reply was taken; read the task instead of sending it againretry_after is the number of seconds the server's Retry-After header
asks you to wait, when the error came with the V1 envelope and the header
is a whole number of seconds; otherwise it is None. 0 means you can
retry at once, so test it with is not None, not by truthiness. Dates
and other header forms are not read.
SDK-coined codes:
| Exception | Cause |
|---|---|
XAgentTransportError |
network / DNS / TLS error below the HTTP layer, or an events() stream whose last frame was not a closing frame |
MalformedResponse |
HTTP succeeded but the body did not match the shape the SDK needs; events() also raises it when the stream endpoint answers 200 with a content type other than text/event-stream or a declared charset other than UTF-8, or with a status that is neither an error nor 200 (a redirect or a 204) -- the latter carrying that status on http_status; create()/append()/reply() raise it when the 202 body does not validate, after the server accepted the write, so do not resend it blindly: a retried create() starts a second task, and a retried append()/reply() can send the message twice; every method that decodes JSON -- me(), agents.*, templates.*, tasks.create()/append()/reply()/get()/steps() and the WorkspaceClient methods -- raises it when the status is not the endpoint's success status (200, or 202 for create()/append()/reply()), for example a redirect or a 204, carrying that status on http_status, and when that body is not JSON; the skills.* methods raise it when the status is not 200 (a redirect or a 204 -- carrying that status on http_status), when a 200 body is not JSON, or when its shape is wrong -- skills.list() never turns a wrong body into an empty list -- and skills.create()/skills.upload()/skills.update() can be retried safely after it; agents.get_skills() and agents.replace_skills() raise it in the same three cases -- get_skills() never turns a wrong body into an empty list -- and after it on replace_skills() call get_skills() to check what the server stored; agents.get_connectors() and agents.replace_connectors() raise it in the same three cases -- get_connectors() never turns a wrong body into an empty selection -- and after it on replace_connectors() the replacement may already have been applied, and calling it again declares the same selection once more (nothing is written if nobody changed the agent in the meantime; a change someone else made in the meantime is overwritten); agents.get() and models.list() raise it in the same three cases -- agents.get() never turns a wrong body into an empty agent, and models.list() never turns one into an empty list; agents.list_assignable_models() raises it in the same three cases and for an entry whose owner_can_use is missing or cannot be read as a bool, never turning a wrong body into an empty list, and agents.update() raises it in those cases too, after the server may already have applied the change (repeating the call is safe, or call agents.get() to see what is stored); agents.add_key() raises it when the body is not a key with a non-empty full_key, after the server may already have created the key, so do not resend it blindly: list the keys with agents.list_keys() first; mcp_servers.list(), mcp_servers.get() and mcp_servers.list_tools() raise it in the same three cases -- mcp_servers.list() never turns a wrong body into an empty list -- and mcp_servers.create(), update(), delete() and set_enabled() raise it in those cases too, after the server may already have applied the write: update() and set_enabled() can be repeated safely, a repeated delete() raises ConnectorNotFound (or ConnectorForbidden while your team still shares the connector), and a repeated create() raises ConnectorNameConflict; TaskInfo.parsed() raises it when the structured result fields break the server's contract (a ready status without an object, or another status without a reason) |
RunMismatch |
wait() / run() with an expected run: the snapshot about to be returned shows another run or no run (code run_mismatch); TaskInfo.parsed(expected_run_id=...) and RunResult.parsed() for the same reason; a subclass of StructuredOutputError |
UnsupportedFeature |
create() / append() / run() with a response_format: GET /v1/features answered 404 or does not list structured_output (raised before the write, task_id=None), or the write's response did not echo the format back (task_id is the accepted task) |
UnsupportedSchema |
a response_format refused before any request: it breaks a server rule checked locally (rule, path and message as the server reports them); a Pydantic model that cannot be converted raises its subclass UnsupportedModel |
UnsupportedModel |
a Pydantic model that cannot be converted into the schema subset, passed as response_format (raised before any request) or to parsed(model); a subclass of UnsupportedSchema whose rule is always "model" (not a server rule id) and whose path is the position the message names, such as /properties/data |
StructuredOutputError |
parsed() could not return a structured result: code is the server's reason code with its message, missing_fields, unexpressible_fields and partial_output, or client_validation_failed (the ready result does not validate with the model passed to parsed(model)), or no_structured_output; a run that does not match raises its subclass RunMismatch (code run_mismatch, also raised by wait() / run()), so except StructuredOutputError catches both |
TaskTimeout |
wait() / run() deadline elapsed, or events()'s own timeout budget -- which covers every read the stream still owes, including time spent between frames, and hands over to a bounded post-close drain once a closing frame has arrived, which ends the stream cleanly rather than raising -- ran out first |
The SDK does not retry automatically. Wrap calls with your own
policy (e.g., tenacity) if you
want retry on transport errors or TaskBusy.
events() delivers each frame as it arrives instead of waiting for the
task to finish. closed_by tells you which frame ended the stream:
from xagent_sdk import AgentClient
with AgentClient() as agent:
task = agent.tasks.create(agent_id=42, message="Summarize the doc.")
with agent.tasks.events(task.task_id) as stream:
for ev in stream:
print(ev.event, ev.data)
print(stream.closed_by) # 'task.completed' on a clean finishThis is the minimal shape only -- reconnecting after a dropped
connection and reconciling against steps() is its own recipe, covered
in a later change.
from xagent_sdk import UserClient
with UserClient() as user: # reads XAGENT_PERSONAL_KEY / XAGENT_BASE_URL
agents = user.agents.list()
if not agents:
raise SystemExit("no agent visible to this key")
result = user.tasks.run(agent_id=agents[0].agent_id, message="Say hi")
print(result.output)A skill is a SKILL.md document that tells an agent how to do one kind of
work. user.skills manages your own personal skills; the server checks
the name and the SKILL.md content.
from xagent_sdk import SkillNotFound, UserClient
SKILL_MD = """\
---
name: weekly-report
description: Drafts the weekly status report from the team's notes.
when_to_use: When the user asks for a weekly report or status update.
---
# Weekly report
Group the notes under Done, In progress and Blocked.
"""
with UserClient() as user:
created = user.skills.create(name="weekly-report", skill_md=SKILL_MD)
print(created.name, created.source) # weekly-report personal
detail = user.skills.get("weekly-report")
print(detail.description)
print(detail.files) # relative paths, e.g. ['SKILL.md']
# update() replaces the whole SKILL.md.
user.skills.update(
"weekly-report", skill_md=SKILL_MD + "\nKeep each item to one line.\n"
)
for skill in user.skills.list(): # your own skills come first
print(skill.name, skill.source)
user.skills.delete("weekly-report") # returns None
try:
user.skills.delete("weekly-report")
except SkillNotFound:
print("already gone")Calling create() again with the same name and the same content returns
200 again, so it is safe to retry after a timeout; the same name with
different content raises SkillAlreadyExists. skills.get() also finds
skills you do not own, such as built-in ones, and reports where they come
from in source.
To create a skill from a file instead, pass its bytes to upload(). Only
.zip and .md files are accepted, and the file name decides which:
from pathlib import Path
from xagent_sdk import UserClient
with UserClient() as user:
uploaded = user.skills.upload(
filename="my-skill.zip",
content=Path("my-skill.zip").read_bytes(),
name="my-skill",
)
print(uploaded.name, uploaded.source) # my-skill personalfilename can also be a full path or a Path. Only its last part is sent, and
both / and \ separate the parts on every platform, so your directories do
not reach the server. A filename with no last part (empty, or ending in a
separator such as dir/) raises ValueError before any request.
Repeating the same upload returns 200 again. The same name with different
content, or a name that was created with create(), raises
SkillAlreadyExists. The server accepts at most 50 MiB, for the upload and for
its unpacked contents (a deployment can lower this); over the limit raises
InvalidInput with http_status=413. A proxy in front of the server can set a
lower limit. If it answers with the V1 error envelope and code invalid_input,
that is also InvalidInput with http_status=413; if it sends its own error
page instead, it is InternalError with http_status=413. The SKILL.md text,
in a .md upload or inside a .zip, has a further limit of 200000 characters;
over it raises InvalidInput with http_status=400.
An agent stores a list of skill names. replace_skills() replaces the whole
list, so read it first and send it back with your change:
from xagent_sdk import UserClient
AGENT_ID = 42
with UserClient() as user:
names = user.agents.get_skills(AGENT_ID)
if "weekly-report" not in names:
names.append("weekly-report")
result = user.agents.replace_skills(AGENT_ID, names)
print(result.skills)
print(result.unresolved_for_caller) # added names you cannot seeThere is no conflict detection: of two concurrent replacements the later one
wins. A name in unresolved_for_caller is stored anyway, because a task loads
the skills of the user who runs it. New tasks use the new list at once; an
existing task can keep using the previous list for a while.
Ask for the answer as JSON that follows a schema, and read it back as a Pydantic model:
from pydantic import BaseModel, Field
from xagent_sdk import AgentClient, StructuredOutputError
class Line(BaseModel):
description: str
amount: float
class Invoice(BaseModel):
number: str
total: float = Field(ge=0)
currency: str = "USD"
lines: list[Line]
with AgentClient() as agent:
try:
result = agent.tasks.run(
agent_id=42,
message="Extract the invoice: INV-001, two lines ...",
response_format=Invoice,
)
invoice = result.parsed() # an Invoice
except StructuredOutputError as exc:
print(exc.code, exc.message, exc.missing_fields, exc.unexpressible_fields)run() keeps the model it was given as RunResult.model, so
result.parsed() returns an Invoice (result is a RunResult[Invoice]
to a type checker); result.parsed(OtherModel) validates the result as
another model instead. With a dict format, parsed() returns a dict.
response_format also takes a JSON object (a dict) you write yourself:
{"type": "json_schema", "json_schema": {"name": "Invoice", "schema": {...}}}
(json_schema may also carry description and "strict": true), or
{"type": "text"} to ask for no structured result. On append() it changes
the format for this and later turns; None keeps the task's format.
Once the task is COMPLETED, TaskInfo (and RunResult) carry three
fields: structured_output_status is "ready", "incomplete" or "failed"
(StructuredOutputStatus); structured_output is the result when ready;
structured_output_reason (StructuredOutputReason) says why not otherwise,
with code (StructuredOutputReasonCode), message, and up to 20 JSON
Pointers in missing_fields (values the answer did not state) and
unexpressible_fields (values it stated in a form the schema cannot hold).
The three fields are None while the task runs, when it has no format, and on
a server that predates them. Without accept_partial, structured_output is
None unless the status is "ready". parsed() returns the result as a dict (a copy), or
validated as the model you pass (on a RunResult, by default the model
run() was given), and raises StructuredOutputError otherwise:
with the server's reason code, or with one of the codes only the SDK raises --
client_validation_failed (the model does not validate the ready result) and
no_structured_output (the snapshot has no structured_output_status). On a
ready result, a model that cannot be converted raises UnsupportedModel
instead, as it does from run(). The run is compared first:
TaskInfo.parsed(expected_run_id=...) with the run you pass, and
RunResult.parsed() with the run run() started. A snapshot of another
run or of no run raises RunMismatch (code run_mismatch), a subclass of
StructuredOutputError, so the except StructuredOutputError above
catches it too.
By default an incomplete result gives you nothing but the reason. Pass
accept_partial=True to create(), append() or run(), together with a
response_format of type json_schema (a dict or a Pydantic model), to
also get what the server could extract:
from pydantic import BaseModel
from xagent_sdk import AgentClient, StructuredOutputError
class Entry(BaseModel):
key: str
level: str
class Review(BaseModel):
summary: str
items: list[Entry]
with AgentClient() as agent:
result = agent.tasks.run(
agent_id=42,
message="Review every entry in the attached list ...",
response_format=Review,
accept_partial=True,
)
try:
review = result.parsed()
except StructuredOutputError as exc:
if exc.partial_output is not None:
print(exc.code, exc.partial_output) # values, `None` at each gapaccept_partialisNone(leave the request as it is),True(write"accept_partial": trueinto the format) orFalse(write nothing, the server treats an absent key as false). A value that is neitherNonenor aboolraisesTypeError. Aboolwith noresponse_format, with{"type": "text"}, or contradicting anaccept_partialkey you wrote into the dict yourself raisesValueError; all of these are raised before any request.- When
structured_output_statusis"incomplete",structured_outputholds the extracted values withNonewhere a value is missing or cannot be written. It is stillNonewhen nothing could be kept, so check it first.parsed()keeps raisingStructuredOutputErrorfor such a task; itspartial_outputis a copy of those values (Nonein every other case). - The status and reason
codedo not depend on the switch. What changes is that a run the agent rated partial or blocked is extracted too: it readsincompletewithagent_partialoragent_blocked, and its reason may then carrymissing_fieldsandunexpressible_fieldsas well. The server runs one more extraction for each such run. - A
Noneat a position the schema does not allow to beNoneis always a gap. ANoneat a position that allows it may mean the answer did not state the value, or stated one that cannot be written. The two lists name at most 20 positions each and may be incomplete; how to treat these values is up to you. The server does not check the quality of the values either. completion_outcomeonTaskInfoandRunResultis how the agent rated the run:"completed","partial"or"blocked". It isNonewhen the task's format does not setaccept_partial(the server then omits the key), or when the run is not completed or recorded no rating; a missing key and a null both read asNone. Whether the result is complete is told bystructured_output_status, not by this field.append()with aresponse_formatreplaces the stored format as a whole, includingaccept_partial: sendaccept_partialagain to keep it. The response does not echo the switch and the SDK sends no warning when it is dropped.run()only callscreate(), so itsaccept_partialis passed tocreate()unchanged.- A server that predates the switch answers
InvalidInput(422) when you send it.
Before the request, the SDK checks the format:
- The value is turned into the JSON that will be sent and checked against the
server's schema rules that do not depend on its size. A value that breaks
one raises
UnsupportedSchemabefore any request;rule,pathandmessageare what the server would report (for exampleS3 at /properties/a/minLength: ...). The size limits are checked by the server, which answersInvalidInput(422). A value JSON cannot encode raisesTypeErrororValueErrorbefore any request when writing the value out fails. A NaN, an infinity or a lone surrogate in a position the local check does not cover raisesValueErrorafter theGET /v1/featurescheck, when the task request body is encoded, with httpx 0.28 or later; older httpx versions send it and the server answersInvalidInput(422). - The first call with a
response_formaton atasksnamespace asksGET /v1/featureswhether the server and key support structured output. A server without that endpoint (404), or a key that cannot set a format, raisesUnsupportedFeaturebefore the task is created. Any other failure of that call is raised as it is, and asked again next time. - The response to the write must echo the format back. If it does not, the
request was accepted but the format may not be in force:
UnsupportedFeature.task_idnames the task.
A Pydantic model is converted into the schema subset the server supports:
- Every object lists all its fields as required and allows no other keys.
Optional[X]stays nullable. - A field with a default value (
note: str = "",tags: list[str] = Field(default_factory=list),options: Options = Options()) becomes nullable. The rawstructured_outputholdsnullthere when the answer did not state it;parsed(Model)removes those nulls so Pydantic applies the default.Optional[X] = <not None>, or a field whose type alias already allowsNone, is already nullable, so it staysNone. - A nested model with a field
descriptionortitleis copied into the schema in full at that place (the field's description replaces the model's), so a model used often this way makes the schema larger; the server limits the schema to 16 KiB. - Constraints such as
format,min_length,georpatternare written at the end of the description, for exampleMin length: 1.orPattern: "^\\d{3}$".(the pattern as a JSON string). The server does not enforce them;parsed(Model)does, and raisesclient_validation_failedwhen the result breaks one. - The format name is the class name with characters outside
A-Za-z0-9_-replaced by_(Page[Item]becomesPage_Item_). dict[str, X],Any, fixed-length tuples such astuple[int, str](atuple[int, ...]is sent as an array), unions of several non-null types (including discriminated unions), recursive models,Decimal,Literals that mix value types, constraint values that cannot be written (such as aformatoutsidea-z0-9-) and constraints that make a description longer than the 1024 characters the server accepts raiseUnsupportedModel, a subclass ofUnsupportedSchema, naming the position and the reason:create(),append()andrun()before any request, andparsed(Model). An error Pydantic raises while generating the model's JSON schema (for example for aCallablefield) propagates unchanged.
To wait for the turn you started rather than whatever the task shows next,
pass its run_id:
turn = agent.tasks.append(task_id, agent_id=42, message="...", response_format=Invoice)
info = agent.tasks.wait(task_id, expected_run_id=turn.run_id)
invoice = info.parsed(Invoice, expected_run_id=turn.run_id)wait() raises RunMismatch (code run_mismatch), a subclass of
StructuredOutputError, instead of returning a snapshot (terminal or
WAITING_FOR_USER) of another run, so a question asked by a turn someone
else appended does not reach you. run() does this for you with the run it
started, and RunResult.parsed() checks it again. The error carries
task_id, expected_run_id and actual_run_id; call get(task_id) to see
what the task shows. Besides another caller's turn, it is raised when:
- the server refused to start your turn: the task still shows the previous
run's result, or, for a new task,
FAILEDwith norun_id. If that previous run had no format and the new turn set one, the task reportsincompletewithnot_produceduntil a turn with the format finishes; - the server is older than v0.8.5 and your appended turn is still queued:
get()shows the previous turn until it starts (see Example 6), sowait(expected_run_id=turn.run_id)raises at once. With such a server, wait untilcompleted_atchanges before calling it.
Known limitations:
- The SDK checks the structure of a schema and its characters (NUL, lone
surrogates, NaN, Infinity) locally; a schema that is too large or too deep
is refused by the server with
InvalidInput(422). - If a turn appended to a
PAUSEDtask is refused before it starts, the task staysPAUSEDandwait()runs untilTaskTimeoutrather than raisingrun_mismatch. - A
reply()keeps its run, sowait(expected_run_id=...)with the run it returns cannot tell the question you answered from a new question that run asks next; comparepending_interaction.question(see Example 7). - Constraint keywords are hints to the model, not checks: only
parsed(Model)enforces them. - The result never holds a blank string (
""," "): a blank answer reads as not stated. Use a nullable field, or a field with a default value andparsed(Model), when you need an empty string. - A nullable object whose fields are all nullable or fixed to one value is
always
nullwhen none of them is stated, so it cannot say "this exists but has no details"; add a boolean field for that. A list of such objects is likewise read as not stated. - Whether the answer stated a value, which allowed value it meant, and
whether it could be written in the required form are decided by the model
that extracts the result. A misreading can give a
readyresult with a missing or wrong value; check results that matter. - Calling an older server over plain HTTP, the
response_formatfield is ignored silently. This SDK detects that throughGET /v1/featuresand the echoed fields, as described above.
An MCP connector gives agents the tools of an external MCP server. With a personal key you can read the connectors you can see (your own, switched on or off, and the ones your team shares with you), list the tools of one, and create, change, switch on or off and delete your own.
import time
from xagent_sdk import (
ConnectorNameConflict,
ConnectorNotFound,
ConnectorUnavailable,
RateLimited,
UserClient,
XAgentTransportError,
)
with UserClient() as user:
for server in user.mcp_servers.list():
print(server.id, server.name, server.transport, server.access, server.enabled)
try:
server = user.mcp_servers.get(42)
except ConnectorNotFound:
print("no connector 42 that you can see")
else:
if server.authorization is not None:
print("OAuth:", server.authorization.status)
try:
listing = user.mcp_servers.list_tools(42)
except RateLimited as e:
# Your account already has two listings in progress, or the
# server's shared tool-listing slots stayed taken.
if e.retry_after is not None:
time.sleep(e.retry_after)
except ConnectorUnavailable as e:
print("cannot list its tools:", (e.details or {}).get("reason"))
except XAgentTransportError:
# The client gave up first; the server may still be working, so
# wait before trying again.
pass
else:
for tool in listing.tools:
print(tool.mcp_name, "-", tool.description)
if listing.failures:
print("some tools may be missing:", listing.failures)
# Create a connector. This is not idempotent: after a timeout, sending it
# again raises ConnectorNameConflict if the first attempt went through.
try:
server = user.mcp_servers.create(
name="my-tools",
transport="streamable_http",
url="https://mcp.example.com/mcp",
headers={"X-Team": "blue"},
)
except ConnectorNameConflict as e:
# connector_id is present only when the name is one of your own
# connectors; read it with get() before relying on it.
print("name taken:", (e.details or {}).get("connector_id"))
else:
# Change only what you pass. headers and auth are replaced as a
# whole, so start from the value you read to change one entry.
server = user.mcp_servers.update(
server.id,
description="Tools for the blue team",
headers={**(server.headers or {}), "X-Trace": "1"},
)
# Switch it off and on again; list_tools() raises ConnectorUnavailable
# (reason "disabled") while it is off.
user.mcp_servers.set_enabled(server.id, False)
user.mcp_servers.set_enabled(server.id, True)
user.mcp_servers.delete(server.id)access is "own" for a connector you are linked to and "team" for one
you only see through your team; a team connector is read-only for you, and
its enabled and user_env are None. update() sends only the fields you
pass; name, transport, url, description, headers, auth and
allow_delegated_authorization cannot be None (to clear description pass
""), while runtime_input_schema, runtime_bindings and signed_uploads
are cleared with None. A header value or secret auth field of
"********" keeps the stored value. These secret values are masked:
header values, env and user_env values, and the bearer_token,
api_key_value, client_secret and access_token entries of auth read
"********" when set. Anything else, such as a secret written into url
or runtime_bindings, comes back as stored. Fields such as transport, access, kind and
authorization.status are plain strings; the server may add values.
OAuth authorization can only be completed in the xAgent web app.
list_tools() makes the server connect to the connector, so it can take much
longer than the other calls: a few seconds at most waiting for a free slot,
then up to the server's initialization timeout to start the connector -- over
60 seconds in the worst case with the default configuration, and without a
limit on a server configured with no timeout. By default it waits for at least 150 seconds; pass timeout= (seconds, greater
than 0) to change that for one call. If your client times out first the server
keeps loading the tools, keeps its slot and keeps counting the listing against
your account, so do not retry at once. Each account may have at most two
listings in progress per server process, across all of its keys and
connectors; a third one, or one that finds no free slot in time, gets
RateLimited, and retry_after is the suggested wait in seconds. A listing is never empty: a connector that yields no tools raises
ConnectorToolsUnavailable. Refer to a tool by mcp_name; name is the web
app's display name and can change.
An agent stores the names of the connectors it uses, and whether it also
selects every MCP connector. replace_connectors() replaces the whole
selection, so read it first and send it back with your change. all_connectors
has no default: pass the value you read, unless you mean to change it.
from xagent_sdk import AgentToolsUnconfigured, ConnectorNotShared, UserClient
AGENT_ID = 42
with UserClient() as user:
current = user.agents.get_connectors(AGENT_ID)
names = [*current.connectors]
if "crm" not in names:
names.append("crm")
try:
result = user.agents.replace_connectors(
AGENT_ID, names, all_connectors=current.all_connectors
)
except AgentToolsUnconfigured:
print("This agent uses the default tool set; choose its tools in the web app.")
except ConnectorNotShared as e:
print(e.details) # {"connectors": [{"name": ..., "reason": ...}]}
else:
print(result.connectors)
print(result.unresolved) # names on the agent that you cannot seeA name you add must be one you can see; otherwise the call raises
InvalidInput (HTTP 400). Names already on the agent are kept even if you
cannot see them, and unresolved lists them. A name can also be a Custom API,
which mcp_servers.list() does not list; all_connectors=True selects every
MCP connector but not Custom APIs, which are selected only by name. For an
agent that belongs to a team, the team's deployment checks the whole new list,
so ConnectorNotShared can name connectors you did not send. Reading
connectors=[] with all_connectors=True can mean the agent uses the default
tool set, and then every write raises AgentToolsUnconfigured. There is no
conflict detection: of two concurrent replacements the later one wins. New
tasks use the new selection at once; an existing task can keep using the
previous one for a while.
agents.get() returns one agent's full configuration, and models.list()
returns the models you can use. The id of a model is what an agent's model
slot stores.
from xagent_sdk import UserClient
AGENT_ID = 42
with UserClient() as user:
agent = user.agents.get(AGENT_ID)
print(agent.name, agent.status, agent.models)
print(agent.unresolved_models) # slots whose model you cannot use
for model in user.models.list():
print(model.id, model.model_id, model.category, model.owned_by_you)AgentDetail uses the wire field names except for two: the wire id is
agent_id, and the wire user_id (the agent's owner, who is not necessarily
you) is owner_user_id.
AgentDetail attribute |
Wire field |
|---|---|
agent_id |
id |
owner_user_id |
user_id |
| every other attribute | the same name |
models is the agent's model settings as stored; an agent with none has None
or an empty object. It maps slots (general, small_fast, visual, compact) to model ids, but
a slot may be missing, a slot that is not set may hold None, "", 0 or
False, and other keys may appear, so read a slot with models.get(slot)
rather than models[slot]. Its values are returned as stored, even a value
that is not an integer id. unresolved_models lists the slots whose model you
cannot use: a task you start falls back to another model there. team_id is
None for a personal agent. Every field, including team_id and models, is
always present, even when its value is None, so a missing field, or one that
cannot be read as its declared type, raises MalformedResponse.
ModelInfo has the wire field names. Only a model whose category is "llm"
takes effect in an agent's model slot when a task runs.
agents.create_from_template() also accepts a model of another category in
overrides["models"], and agents.get() then lists that slot in
unresolved_models. A model's id is specific to the deployment you call;
use model_id to find the same model in another one.
An empty list means you have no models. A body that is not an array of models
raises MalformedResponse and is never read as an empty list.
agents.update() changes only the fields you pass. Read the agent, change one
model slot, then read the result to confirm. agents.list_assignable_models()
lists the models a slot can take: each has owner_can_use, and a slot can only
be changed to a model whose owner_can_use is True.
from xagent_sdk import ModelNotAssignable, UserClient
AGENT_ID = 42
WANTED = "gpt-4o-mini" # the model_id string of the model you want
with UserClient() as user:
agent = user.agents.get(AGENT_ID)
print(agent.models)
# A model's integer id is specific to the deployment you call, so look it
# up here by its model_id string.
choices = user.agents.list_assignable_models(AGENT_ID)
chosen = next(
m for m in choices if m.model_id == WANTED and m.owner_can_use
)
try:
updated = user.agents.update(AGENT_ID, models={"visual": chosen.id})
except ModelNotAssignable as exc:
for refused in (exc.details or {}).get("models", []):
print(refused["slot"], refused["id"], refused["reason"])
raise
# Only the visual slot changed; the other slots keep their stored model.
print(updated.models)
print(updated.unresolved_models) # slots that still fall back for youTo change the execution mode, pass it the same way:
user.agents.update(AGENT_ID, execution_mode="think"). Only the four
lowercase values flash, balanced, think and auto are accepted.
Pass only the arguments you want to change: update(AGENT_ID, name="Billing")
leaves the description, instructions and models alone, and update(AGENT_ID)
changes nothing and returns the current configuration. name, description
and instructions cannot be None; pass "" to empty the last two. In
models, a slot set to an int takes that model, a slot set to None clears
it, and a slot you leave out keeps its model. Clearing a slot means a task uses
the model of the task itself or the default model, which can differ with whoever
starts it.
The models value of agents.get() cannot always be passed back as is. It is
None for an agent without models, which raises TypeError before any request.
A value saved in the web app can hold keys other than the four slots, or slot
values other than None or an integer from 1 to 2**31 - 1, and the server
refuses those with InvalidInput (HTTP 422). Pass only the slots you change.
A slot sent with the model it already stores is left as it is and is not
checked. Any other slot can only be changed to a model that
list_assignable_models() lists with owner_can_use set to True. Otherwise
the call raises ModelNotAssignable (HTTP 400) and nothing is changed;
details["models"] lists each refused slot as {"slot", "id", "reason"}, where
id is the requested model's id:
reason |
Meaning |
|---|---|
unavailable |
you cannot use the model: it does not exist, is switched off, or is not visible to you |
not_llm |
you can use it, but it is not an llm model |
owner_cannot_use |
you can use it, but the agent's owner cannot; the entry also has owner_user_id |
Treat any other reason string as unavailable. A request that the server
also refuses for its name or for a description or instructions that are too
long raises InvalidInput instead, and its model slots are not checked.
Of two concurrent updates the later one overwrites the earlier one's value for
the same field or slot; nothing detects the conflict. New tasks use the new
values at once. A task that is already running can keep using the previous
values for a while, and an ongoing workforce conversation that includes the
agent can be rejected with workforce_config_changed on its next turn after
instructions or models change (a preview conversation in the workforce
builder is not checked, and neither is a conversation that started before the
check). If the change was stored but you can no longer see the agent when the
server reads it again, the call raises AgentNotFound although the change took
effect.
A task resolves each slot as the user it runs as. If that user cannot use the
model, a task started on this agent falls back to a default model for that slot
without an error. When another agent calls this agent, such a general model
fails the call, and such a model in another slot is left unused. For a team
agent, prefer models shared with the team.
All methods are synchronous.
Constructed with a personal key; talks to /v1/me, /v1/templates*,
/v1/agents*, /v1/skills*, /v1/mcp-servers*, /v1/models and /v1/chat/tasks*.
See the UserClient docstring for which agents and tasks a personal key
can reach.
| Method | Returns | Notes |
|---|---|---|
UserClient(personal_key, base_url, ...) |
UserClient |
env-var fallback: XAGENT_PERSONAL_KEY / XAGENT_BASE_URL |
user.me() |
UserPrincipal |
identity probe (no caching) |
user.templates.list() |
list[Template] |
GET /v1/templates |
user.templates.get(template_id) |
TemplateDetail |
GET /v1/templates/{template_id}; 404 → TemplateNotFound |
user.agents.list() |
list[AgentSummary] |
GET /v1/agents |
user.agents.create(*, name, instructions, generate_runtime_key=True, metadata=None) |
AgentCreateResult |
POST /v1/agents; runtime_full_key is one-time |
user.agents.create_from_template(template_id, *, overrides=None, generate_runtime_key=True) |
AgentCreateResult |
POST /v1/agents/from-template; 404 → TemplateNotFound |
user.agents.rotate_key(agent_id) |
RotateKeyResult |
POST /v1/agents/{agent_id}/api-key; revokes all of the agent's runtime keys, including any added with add_key(), and issues one new key |
user.agents.add_key(agent_id, *, label=None) |
AddedKeyResult |
POST /v1/agents/{agent_id}/api-keys; adds a runtime key and leaves the agent's other keys working, the opposite of rotate_key(); full_key is one-time; key_id is what revoke_key() takes; label is optional, the server takes 1 to 100 characters with at least one that is not whitespace (the SDK does not check it) and does not require it to be unique, so give every call, retries included, a label no key of the agent has used; agent_id must be an int, else TypeError before any request; not safe to resend, a second call adds another key; after a timeout, an HTTP 500 InternalError, XAgentTransportError or MalformedResponse the key may exist, so wait a few seconds, list the keys and revoke the one with the failed call's label that you do not hold, retry with another label, and after the retry succeeds list again and revoke any key with a failed call's label that you do not hold; if the failed call had no label, or its label may be in use elsewhere, do not revoke by label (an HTTP 409 means no key was created); 401 → InvalidAPIKey; 404 → AgentNotFound; a bad label or an out-of-range id → InvalidInput (422); a server error or a prefix conflict (409) → InternalError; a server without this route answers 404 or 405 without the V1 envelope → InternalError |
user.agents.get_skills(agent_id) |
list[str] |
GET /v1/agents/{agent_id}/skills; 404 → AgentNotFound; a body that is not the expected object raises MalformedResponse (never []) |
user.agents.list_keys(agent_id, *, include_revoked=False) |
list[RuntimeKeyInfo] |
GET /v1/agents/{agent_id}/api-keys; newest first, never includes a secret; revoked keys only with include_revoked=True, paused keys always; 404 → AgentNotFound; a body that is not the expected array → MalformedResponse, never an empty list; a server without this route answers 404 → InternalError |
user.agents.revoke_key(agent_id, key_id) |
RevokeKeyResult |
DELETE /v1/agents/{agent_id}/api-keys/{key_id}; revokes that one key and leaves the agent's other keys working; no call reverses it; calling again is safe and returns revoked=False; a key that a still-settling rotation had already revoked is such a no-op and can be restored if that rotation's new key cannot be delivered, so list the keys again once the rotation settles and revoke the key if it is active; unknown agent → AgentNotFound, a key id the agent does not have → APIKeyNotFound; a server without this route answers 404 or 405 → InternalError |
user.agents.replace_skills(agent_id, skills) |
AgentSkillsUpdate |
PUT /v1/agents/{agent_id}/skills; 404 → AgentNotFound; replaces the whole list, [] clears it, and the later of two writers wins; a single string raises TypeError before any request; a new name that is neither visible nor valid → InvalidInput (400); unresolved_for_caller lists added names you cannot see, stored anyway |
user.agents.get(agent_id) |
AgentDetail |
GET /v1/agents/{agent_id}; agent_id must be an int (anything else raises TypeError before any request); wire id is agent_id and wire user_id is owner_user_id; 404 → AgentNotFound; out-of-range id → InvalidInput (422); a body that is not the expected object, or lacks a field or has one that cannot be read as its declared type, raises MalformedResponse (models only has to be an object or None) |
user.agents.update(agent_id, *, name=..., description=..., instructions=..., execution_mode=..., models=...) |
AgentDetail |
PATCH /v1/agents/{agent_id}; only the parameters you pass are sent, passing none returns the current configuration; none of name, description, instructions, execution_mode accepts None (pass "" to empty description or instructions); execution_mode is one of "flash" (a short path for simple tasks that can still call tools), "balanced" (step-by-step reasoning with tools), "think" (plan first, then run) or "auto" (the model chooses between a direct answer, step-by-step work and a plan), sent as given and not checked by the SDK, and any other value, a different case included, → InvalidInput (422), as is the value get() returns for an agent saved by another path when it is outside the four; a server that predates execution_mode answers 422 Extra inputs are not permitted; models merges slot by slot ({"visual": None} clears a slot, a slot you leave out is kept) and is copied into the request; a slot sent with the model it already stores is not checked, any other slot takes only a model list_assignable_models() lists with owner_can_use=True, and AgentDetail.models from get() cannot always be passed back as is; of two concurrent writers the later one wins, and new tasks use the new values at once while a task already running can keep the previous values for a while; safe to repeat; agent_id must be an int, else TypeError before any request; 404 → AgentNotFound; a model slot that cannot take the model → ModelNotAssignable (400) with details["models"]; a name already in use, or a description or instructions over 10000 characters and longer than the stored one → InvalidInput (400); a malformed value, or an out-of-range id → InvalidInput (422); a body that is not the expected agent raises MalformedResponse, and the change may already be stored |
user.agents.list_assignable_models(agent_id) |
list[ModelForAgent] |
GET /v1/agents/{agent_id}/assignable-models; every llm model you can use, in server order, each with owner_can_use, which says whether the agent's owner can use it too; a model the owner cannot use is listed with owner_can_use=False, and update() takes only a model with owner_can_use=True; [] means you can use no llm model; agent_id must be an int, else TypeError before any request; 404 → AgentNotFound; an out-of-range id → InvalidInput (422); a body that is not an array of models, or an entry whose owner_can_use is missing or cannot be read as a bool, raises MalformedResponse (never []) |
user.agents.get_connectors(agent_id) |
AgentConnectors |
GET /v1/agents/{agent_id}/connectors; agent_id must be an int (anything else raises TypeError before any request); 404 → AgentNotFound; a body that is not the expected object, or lacks any of its four fields, raises MalformedResponse (never an empty selection); connectors=[] with all_connectors=True can also be an agent that uses the default tool set |
user.agents.replace_connectors(agent_id, connectors, *, all_connectors) |
AgentConnectors |
PUT /v1/agents/{agent_id}/connectors; replaces the whole selection, [] clears it, and the later of two writers wins; all_connectors is required and has no default; a single string, or an agent_id that is not an int, raises TypeError before any request; 404 → AgentNotFound; an added name you cannot see → InvalidInput (400); a team that cannot use the selection → ConnectorNotShared; an agent on the default tool set → AgentToolsUnconfigured; unresolved lists names on the agent that you cannot see |
user.tasks.create / append / reply / cancel / get / steps / events / wait / run |
as in the AgentClient table |
Any agent you can see (user.agents.list()); the task runs as you, not as the agent's owner. Every personal key of yours sees the tasks any of them created, until the task's agent is deleted. An older server answers InvalidAPIKey (401) here. |
user.skills.list() |
list[SkillSummary] |
GET /v1/skills; your own skills first, in server order; a body that is not an array of skills raises MalformedResponse (never []) |
user.skills.get(name) |
SkillDetail |
GET /v1/skills/{name}; includes skill_md and files; 404 → SkillNotFound; "", ".", ".." or a name containing / raises ValueError before any request |
user.skills.create(*, name, skill_md) |
SkillSummary |
POST /v1/skills; the same name with the same content returns 200 again, so a retry is safe; any other clash → SkillAlreadyExists; bad name or content → InvalidInput |
user.skills.upload(*, filename, content, name=None) |
SkillSummary |
POST /v1/skills/upload; .zip or .md, chosen by filename, which can be a path or a Path (only its last part is sent); content is bytes; the same name with the same content returns 200 again, any other clash → SkillAlreadyExists; over the size limit → HTTP 413 (see the upload section); a filename with no last part raises ValueError before any request |
user.skills.update(name, *, skill_md) |
SkillSummary |
PUT /v1/skills/{name}; replaces the whole SKILL.md of one of your own skills (anything else → SkillNotFound); bad content → InvalidInput; same ValueError rule as get |
user.skills.delete(name) |
None |
DELETE /v1/skills/{name}; returns once the server confirms; deleting again → SkillNotFound; same ValueError rule as get |
user.mcp_servers.list() |
list[McpServer] |
GET /v1/mcp-servers; your own connectors first (including ones switched off), then the ones your team shares with you, in server order; a body that is not an array of connectors raises MalformedResponse (never []) |
user.mcp_servers.get(server_id) |
McpServer |
GET /v1/mcp-servers/{server_id}; 404 → ConnectorNotFound (also for a connector you cannot see); a server_id that is not an integer raises TypeError before any request |
user.mcp_servers.list_tools(server_id, *, timeout=None) |
McpServerTools |
GET /v1/mcp-servers/{server_id}/tools; the server connects to the connector, so this is slow (a few seconds for a free slot plus up to the server's initialization timeout, over 60 seconds by default in the worst case, and without a limit when the server is configured with no timeout); timeout is this call's read timeout in seconds (finite, greater than 0, else ValueError), and when not given the larger of the client's read timeout and 150 seconds is used (no limit if the client has none); if the client times out first (XAgentTransportError) the server keeps working, keeps its slot and keeps counting the listing against your account, so do not retry at once; two listings of your account already in progress, or no free slot in time → RateLimited with retry_after; no tools loaded → ConnectorToolsUnavailable (an empty tools list never comes back as a success); a non-empty failures means part of the loading failed; refer to a tool by McpTool.mcp_name, not name |
user.mcp_servers.create(*, name, transport, url, description=None, headers=None, auth=None, runtime_input_schema=None, runtime_bindings=None, signed_uploads=None, allow_delegated_authorization=False, enabled=True) |
McpServer |
POST /v1/mcp-servers; name, transport, url, allow_delegated_authorization and enabled are always sent, the other parameters only when not None; not idempotent: after a timeout, a repeat raises ConnectorNameConflict if the first attempt went through (details["connector_id"] then names one of your connectors, which may also be one that already existed, so check it with get()); transport other than streamable_http or sse → TransportNotSupported; OAuth authorization can only be completed in the web app |
user.mcp_servers.update(server_id, *, name=..., transport=..., url=..., description=..., headers=..., auth=..., runtime_input_schema=..., runtime_bindings=..., signed_uploads=..., allow_delegated_authorization=...) |
McpServer |
PATCH /v1/mcp-servers/{server_id}; only the parameters you pass are sent, and passing none returns the current state of a remote connector you are linked to; None is not allowed for name, transport, url, description, headers, auth and allow_delegated_authorization, and clears runtime_input_schema, runtime_bindings and signed_uploads; headers and auth replace the whole value ({} clears it); safe to repeat; team-shared → ConnectorForbidden (team_shared), catalog → ConnectorNotEditable (catalog), changing url, auth.issuer or auth.resource_metadata_url while other accounts hold authorizations it would keep → ConnectorNotEditable (authorized_by_others), and otherwise such a change removes the authorizations your team members made for themselves; name taken → ConnectorNameConflict |
user.mcp_servers.delete(server_id) |
None |
DELETE /v1/mcp-servers/{server_id}; removes your own connector and returns once the server confirms; if your team still shares it, it stays in list() with access="team" and a repeated delete → ConnectorForbidden (team_shared), otherwise a repeat → ConnectorNotFound; catalog or managed by another account → ConnectorNotEditable; a team-owned connector deleted by a non-administrator → ConnectorForbidden (not_permitted) |
user.mcp_servers.set_enabled(server_id, enabled) |
McpServer |
PUT /v1/mcp-servers/{server_id}/enabled; switches only your own switch, works for catalog connectors too, and setting the current value is not an error; team-shared → ConnectorForbidden (team_shared); safe to repeat |
user.models.list() |
list[ModelInfo] |
GET /v1/models; every model you can use, of every category, in server order; only category="llm" models take effect in an agent's model slots, and agents.get() lists a slot holding another category in unresolved_models; a body that is not an array of models raises MalformedResponse (never []) |
user.close() / with ... as user |
— | release the connection pool |
Constructed with an agent runtime key; talks to /v1/chat/tasks*
only.
| Method | Returns | Notes |
|---|---|---|
AgentClient(api_key, base_url, ...) |
AgentClient |
env-var fallback: XAGENT_API_KEY / XAGENT_BASE_URL |
agent.tasks.create(*, agent_id, message, metadata=None, dispatch_class=None, priority=None, prompt_context=None, response_format=None, accept_partial=None) |
CreateTaskResult |
POST /v1/chat/tasks; returns immediately, status='pending' when the server queues the task for its dispatcher or 'running' when it runs the task in-process; dispatch_class ('interactive'/'batch') and priority (-10..10) apply to the new task only, the server validates them (422 → InvalidInput) and an older server ignores them; the result's dispatch_class shows the class the server gave the start command (None if not dispatched through a queue or on an older server); run_id names the run it started; response_format (a dict or a Pydantic model) asks for a structured result, see Example 13 (UnsupportedSchema / UnsupportedFeature); accept_partial=True also keeps the values extracted from an incomplete result (see Partial results) |
agent.tasks.append(task_id, *, agent_id, message, metadata=None, prompt_context=None, response_format=None, accept_partial=None) |
AppendResult |
POST /v1/chat/tasks/{id}/messages; status='pending' (queued) or 'running' (in-process); raises TaskBusy if the prior turn is still queued or running, InteractionResponseRequired if WAITING_FOR_USER; run_id names the new run; response_format replaces the task's format as a whole, including accept_partial ({"type": "text"} removes it, None keeps it) |
agent.tasks.reply(task_id, *, agent_id, message) |
AppendResult |
POST /v1/chat/tasks/{id}/reply; answers a WAITING_FOR_USER task's pending question and resumes its server-side run (the result's run_id is that run, not a new one); not idempotent |
agent.tasks.cancel(task_id) |
CancelResult |
POST /v1/chat/tasks/{id}/cancel; stops a task that is running, queued, waiting for an answer or paused; cancelled=True once it is cancelled (also when it already was), False when the cancel is recorded but not applied yet -- call again, it reaches the same cancel as long as no turn is appended to the task in between; raises TaskNotCancellable if the task already ended without being cancelled or another turn replaced the one the cancel was aimed at (do not retry), TaskBusy if it cannot be cancelled in its current state yet or changed state meanwhile (retry); cancelled_run_id names the run that was cancelled; see Cancelling a task |
agent.tasks.get(task_id) |
TaskInfo |
GET /v1/chat/tasks/{id}; latest-turn input/output; pending_interaction when WAITING_FOR_USER; run_id, the structured_output* fields and completion_outcome; TaskInfo.parsed(model=None, *, expected_run_id=None) reads the structured result |
agent.tasks.steps(task_id) |
list[Step] |
GET /v1/chat/tasks/{id}/steps; full timeline |
agent.tasks.events(task_id, *, timeout=None) |
TaskEventStream |
GET /v1/chat/tasks/{id}/events (SSE); iterate decoded StreamEvent frames as the task runs; closed_by tells how the stream ended |
agent.tasks.wait(task_id, *, timeout=120, poll_interval=1.0, expected_run_id=None) |
TaskInfo |
poll get() until COMPLETED/FAILED or WAITING_FOR_USER; raises TaskTimeout on deadline; with expected_run_id, a returnable snapshot of another run or of no run raises RunMismatch (run_mismatch) |
agent.tasks.run(*, agent_id, message, timeout=120, poll_interval=1.0, metadata=None, dispatch_class=None, priority=None, prompt_context=None, response_format=None, accept_partial=None) |
RunResult |
create + wait(expected_run_id=created.run_id) + steps; RunResult.run_id, RunResult.model (the model passed as response_format, which parsed() uses when called without one), the structured_output* properties, completion_outcome and parsed(model=None); raises RunMismatch if the snapshot shows another run or no run |
agent.close() / with ... as agent |
— | release the connection pool |
Prompt context: create(), append() and run() take
prompt_context, reference data the server stores on the task and shows
the agent on every turn. None (the default) sends nothing, so
append() keeps what the task already has. An object replaces it, and
{} clears it on append() (on create() it stores nothing). With an
agent key the values count as signed by your backend, and the agent's
declared fields do not limit them. With a personal key (user.tasks)
they count as unsigned, with the same trust as user input: every field
must be one the agent declares and be no longer than the declared
length, otherwise the whole request raises InvalidInput (422) and
message names the rejected fields. This SDK can neither set nor read
an agent's declared fields. Declare them on the agent in the web agent
builder. The server checks keys, value types and size. A nan or inf
value raises ValueError before the task request is sent with httpx 0.28 or
later; older httpx versions send it and the server answers
InvalidInput. A value JSON cannot encode, such as a date, raises
TypeError before the task request is sent. A server that predates this
field ignores it silently.
For SaaS apps on the hosted service. Constructed with a workspace key
and manages agents/templates scoped to a workspace. Lives under
xagent_sdk.cloud so the self-hosted package is unaffected — import it
explicitly.
The hosted service is per-region; a workspace key only works against the
region that issued it. Pass the Region shown in your deploy snippet (or
an explicit base_url for a self-hosted / not-yet-listed region). The
minted runtime key runs on the same host, so reuse that base_url for
AgentClient:
from xagent_sdk.cloud import Region, WorkspaceClient
from xagent_sdk import AgentClient
region = Region.SG # from the deploy snippet
with WorkspaceClient(workspace_key="xag_workspace_...", region=region) as ws:
created = ws.agents.create_from_template(
"support-ai-chatbot-agent", name="HR Leave Assistant"
)
runtime_key = created.runtime_full_key # one-time secret
with AgentClient(api_key=runtime_key, base_url=region.base_url) as agent:
print(agent.tasks.run(agent_id=created.agent_id, message="Hi").output)| Method | Returns | Notes |
|---|---|---|
WorkspaceClient(workspace_key, *, region=None, base_url=None, ...) |
WorkspaceClient |
env fallback XAGENT_WORKSPACE_KEY; pass region=Region.AU/SG or base_url=... (not both); neither + no XAGENT_BASE_URL raises — no hosted default |
ws.templates.list() / ws.templates.get(id) |
list[Template] / TemplateDetail |
GET /v1/workspace/templates* |
ws.agents.list() |
list[AgentSummary] |
GET /v1/workspace/agents |
ws.agents.create(*, name, instructions, description=None, execution_mode=None, models=None, knowledge_bases=None, skills=None, tool_categories=None, suggested_prompts=None, generate_runtime_key=True) |
AgentCreateResult |
POST /v1/workspace/agents |
ws.agents.create_from_template(template_id, *, name=None, ..., generate_runtime_key=True) |
AgentCreateResult |
POST /v1/workspace/agents/from-template; override fields spread flat |
ws.agents.rotate_key(agent_id) |
RotateKeyResult |
POST /v1/workspace/agents/{id}/api-key; mints the agent's runtime key |
ws.agents.list_keys(agent_id, *, include_revoked=False) |
list[RuntimeKeyInfo] |
GET /v1/workspace/agents/{id}/api-keys; same result and errors as user.agents.list_keys() |
ws.agents.revoke_key(agent_id, key_id) |
RevokeKeyResult |
DELETE /v1/workspace/agents/{id}/api-keys/{key_id}; same result, errors and rotation caveat as user.agents.revoke_key() |
The minted runtime key is an ordinary agent key — drive it with
AgentClient against /v1/chat/tasks*, exactly as above.
TaskStatus enum:
PENDING,RUNNING— in flight;wait()keeps pollingPAUSED— agent paused waiting for external action (e.g. another caller appending); not terminal —wait()keeps polling until the deadline so you observe the resume transitionWAITING_FOR_USER— the agent asked a question and is blocked on your answer; not terminal, butwait()/run()return here (a passive poller would never advance it). Read the question offpending_interactionand answer withreply()(notappend()--append()raisesInteractionResponseRequiredon this status), thenwait()again:See Example 7 above for the retry caveat (result = agent.tasks.run(agent_id=agent_id, message="Book me a flight") if result.status is TaskStatus.WAITING_FOR_USER: task_id = result.info.task_id pending = result.info.pending_interaction if pending is not None: # can be None: see Example 7 print(pending.question) agent.tasks.reply(task_id, agent_id=agent_id, message="To Tokyo, next Friday") info = agent.tasks.wait(task_id)
reply()is not idempotent).COMPLETED,FAILED— terminal;wait()returns
A cancelled task is FAILED with error_code == "task_cancelled"; every
other failure has error_code None. The closing task.completed frame
of events() carries the same error_code. There is no separate
cancelled status, so code that waits for COMPLETED/FAILED keeps
working.
cancel() works on a task that is running, queued, waiting for an answer
or paused. The server waits about 10 seconds for the cancel to be
applied. When it is not applied by then, cancelled is False; call
cancel() again, which reaches the same cancel rather than a new one as
long as no turn is appended to the task in between. Each request names
only the task, so once the first cancel has been applied, a turn appended
before the retry is the one the retry cancels. The loop below assumes
nothing else appends to the task; a caller that means to cancel only the
original turn should hold back appends until the cancel is confirmed:
result = agent.tasks.cancel(task_id)
while not result.cancelled: # recorded, not applied yet
result = agent.tasks.cancel(task_id)Prefer this to wait() here: a paused task whose automatic resume gives
up meanwhile reads FAILED with no error_code, although the recorded
cancel still applies to it.
The cancel errors, and which to retry:
TaskNotCancellable-- the task already ended without being cancelled, or another turn replaced the one the cancel was aimed at. Do not retry.TaskBusy-- the task cannot be cancelled in its current state yet (for example an answer is queued or being applied, or a queued turn has no run of its own yet), or it changed state while the cancel was applied. Retry.InternalErrorwithhttp_status == 503-- the cancel could not be applied. Retry.
cancel() stops the agent's own work, including a workforce's members.
It does not interrupt code already handed to a code-execution process or
a call to a remote A2A agent; those run to their own end. A cancelled task
accepts append() like any failed task. A task that was waiting for an
answer has its question closed, so reply() then raises
NoPendingInteraction; a paused task is no longer resumed automatically.
After a cancel, CancelResult describes the task as get() reads it,
and cancelled_run_id names the run that was cancelled. While a turn
appended after the cancelled run is still queued to start, the task
reads PENDING with error_code None, as get() does; once that turn
starts, status and run_id are that turn's, so run_id is no longer
cancelled_run_id.
Two cases to know when you cancel a turn that is still queued:
- A task cancelled before its first run started has no
run_id, so a concurrentrun()orwait(expected_run_id=...)for it raisesRunMismatch. - A turn you appended to a finished or paused task and cancelled before
it started is withdrawn without changing the task:
get()keeps showing the turn before it, and onlyCancelResult.cancelled_run_idnames the withdrawn run. If something else waits for that appended turn, have it comparerun_idwith the oneappend()returned. Callingcancel()again returns the same result while the task has not changed since; it does not cancel the turn before it.
UserClient(
personal_key=None, # or env XAGENT_PERSONAL_KEY
base_url=None, # or env XAGENT_BASE_URL
timeout=30.0, # max seconds for any single wait, None for no limit (connect is fixed at 10); not a deadline for the whole request
max_connections=10, # httpx connection pool size
user_agent=None, # override the default "xagent-sdk-python/..."
transport=None, # custom httpx.BaseTransport (proxy / TLS / tests)
)
AgentClient(
api_key=None, # or env XAGENT_API_KEY
base_url=None, # or env XAGENT_BASE_URL
timeout=30.0,
max_connections=10,
user_agent=None,
transport=None,
)Both clients share the same configuration surface. Constructing both
in the same process is safe: each holds its own httpx.Client, so
their default headers (and connection pools) do not bleed into each
other.
Streams and the pool: each open agent.tasks.events(...) stream holds one
connection from the same pool until it is closed. The server allows 2
concurrent streams per task and 32 per API key, so if you intend to run
several at once, raise max_connections above the number of concurrent
streams plus the headroom your ordinary calls need — otherwise an ordinary
request can wait out its pool timeout and fail with XAgentTransportError.
A release that itself fails to close can hold its slot for the life of the
client; the SDK logs a warning naming the task when that happens rather than
letting it pass unnoticed.
transport= accepts any httpx.BaseTransport — useful for custom
retry/proxy/TLS configuration in production, and for
httpx.MockTransport in tests.
Threading: both clients are safe to share across threads.
Fork: close and recreate after os.fork() to avoid socket-state
corruption (standard caveat for any HTTP client with a persistent
connection pool).
-
0.x = alpha. Any minor bump (0.1 → 0.2 → 0.3 → 0.4) may break the surface. Patch bumps (0.3.0 → 0.3.1) are bugfix-only.
-
A future 1.0 will lock the public API per SemVer.
-
Always pin to a git tag in production (pick one from the tags page):
pip install "xagent-sdk @ git+https://github.com/xorbitsai/xagent-sdk@vX.Y.Z#subdirectory=python"Installing from
@mainwill eventually break you when the surface evolves on the 0.x track. The#subdirectory=pythonfragment is required because the SDK lives in a subdirectory of the multi-language monorepo. -
The User-Agent header carries the SDK version (
xagent-sdk-python/X.Y.Z) so the backend can correlate issues.
uv sync --group dev
uv run pre-commit install
uv run pytest # ~120 unit tests, hermetic, ~1sThe package version is not stored in any file: the build derives it from
the nearest vX.Y.Z git tag. Tags starting with v and a digit are
reserved for this Python package; other tags are ignored. To release,
create an annotated tag on the release commit on main and push
that tag to GitHub — no file changes are needed:
git tag -a vX.Y.Z -m "xagent-sdk X.Y.Z"An install from a commit after the latest tag reports a development
version such as X.Y.(Z+1).devN+g<commit>. A source tree without git
metadata builds as 0+unknown.
E2E tests require a running xAgent backend and both keys (one to mint agents, one to run them). Run them explicitly:
export XAGENT_BASE_URL=http://localhost:8000
export XAGENT_PERSONAL_KEY=xag_personal_...
export XAGENT_API_KEY=xag_...
# macOS / corporate networks: bypass any system proxy for localhost,
# otherwise the SDK request can be intercepted and return an empty 5xx.
export NO_PROXY=localhost,127.0.0.1
uv run pytest -m e2eSet E2E_AGENT_ID to point the tests that run an existing agent, and
the test that writes its skill list back unchanged, at a specific agent
(AgentClient has no identity probe, so these tests skip when this is
unset). The skill list test skips before writing unless the write would
leave the list as it is. Set E2E_TEMPLATE_ID to pick which template
the full-flow test instantiates from (defaults to the first listed
template), and E2E_AGENT_NAME to override the new agent's display
name.
Set XAGENT_E2E_MCP_URL to the URL of a streamable_http MCP server the
backend can reach to run the MCP connector tests. They create a connector
with a unique name pointing at it and delete it afterwards; without the
variable they skip.
See LICENSE.