Skip to content

Agent Initialization ​

Prefer the Agent class: every capability is a constructor argument, and the result is an ordinary dataclass you can inspect. setup_agent() is the shortcut for the common case — a CLI-style agent with built-in tools and commands.

With Agent ​

python
from xun import Agent, ToolBox

def weather(city: str) -> str:
    """Query the weather for a given city."""
    return f"Sunny in {city}"

agent = Agent(toolbox=ToolBox().register(weather))   # Agent[T.Uninit]
agent = agent.initialize()                            # Agent[T.Init]

answer = agent.instruct("What is the weather in Paris?").execute()
print(answer.unwrap())

initialize() must be called before execute(); rebinding the variable keeps the static type precise. See Lifecycle & Type State.

Constructor arguments (all optional):

ArgumentDefaultNotes
nameagent-<uuid>Displayed label; sub-agents are expected to set it.
identifier16-hex tokenStable id used by displays; unique per agent.
toolboxempty ToolBoxSee Tools.
displayNullDisplayProgrammatic agents are silent unless you attach a display.
workspaceWorkspace(workdir=Path.cwd())workdir plus a lazily created, GC-cleaned tempdir.
conversationemptyMessage history; system() / instruct() write to it.
commandempty CommandRegistrySlash commands.
configload_config().clone()This agent's own copy — mutate freely.
hooksfresh HooksNot shared with sub-agents.
compactorAutoCompactorToken-budget policy, installed on before_execution_step.
statefresh AgentStateNot inherited; see below.
cancel_eventnew root eventUsually only set by Agent.inherit, which derives it from the parent's.
spannew SpanContextTrace position; Agent.inherit chains it to the parent — see Display Extension.
api_call_semaphoreSlotSemaphore(8)Shared with sub-agents to cap concurrent model calls; the default comes from _XUN_MAX_API_CALL_CONCURRENCY. A slot stays reserved to the agent that last held it, so a conversation keeps landing on the same slot and server-side KV prefixes stay cached (xun.SlotSemaphore).
extension_loaderdefault_loaderScanner for $XUN_HOME/extensions/.

Agent.inherit() copies or shares the group above (config deep-cloned, the rest by reference), shares api_call_semaphore, derives cancel_event and chains span; state and hooks deliberately are not, so a sub-agent starts with a clean slate.

What initialize() does ​

  1. Applies every extension's setup_extension(ctx) — the last moment to change tools or config programmatically.
  2. Auto-detects the model name if the config left it empty.
  3. Binds the display and emits AgentBindEvent, then prepares the workspace directory.
  4. Installs the compactor on the agent's hooks.
  5. Fires after_initialize, then loads AGENTS.md into the system prompt.

initialize() is idempotent, and calling it on a finalized agent raises.

With setup_agent ​

python
from xun import setup_agent, interactive_session

agent = setup_agent(tools=[weather], default_tools=False, workdir=".")
interactive_session(agent, task="What is the weather in Paris?")
ParameterDefaultMeaning
name"agent"Agent name.
tools[]Your own tool functions.
default_toolsFalseRegister all 8 built-in tool sets plus the sub-agent tools. Kept off so tools stays explicit.
default_system_promptTrueInstall the built-in system prompt.
default_commandsTrueRegister the built-in slash commands.
displayDisplay()Console display; pass NullDisplay() to silence, or a WebDisplay to serve.
workdirPath.cwd()Workspace root.
initTruePass init=False to get an uninitialized Agent[T.Uninit] — the form a session that restores an agent from storage uses.

It returns an already initialized Agent[T.Init], and registers ToolBox().with_defaults().with_subagent_provider() when default_tools=True.

Running ​

python
agent.system("You are a terse assistant.")                 # replace the system prompt
agent.instruct("hello", images=["cat.png"])                 # add a user message (agent stays Init)
result = agent.execute(max_iterations=512, context=my_ctx)  # run until the model answers
  • system() and instruct() return the agent, so they chain.
  • execute() returns Result[str, ErrorInfo], or Result[T, ErrorInfo] with a schema — see Structured Output.
  • context is the value injected into tools that declare a ToolCallContext parameter — see Tools.
  • max_iterations bounds the loop; on exhaustion the run ends with an error result.
  • execute_command(name, "args") runs a slash command instead of the model loop.

Finalizing ​

finalize() fires before_finalize, unbinds the display, emits AgentUnbindEvent and makes the agent unusable. A with block does both ends for you. Do not rely on garbage collection: the agent's weakref.finalize hook cannot observe a dying agent, so cleanup happens only when you call finalize().

python
with Agent(display=my_display) as agent:      # initialize()
    agent.toolbox.register(weather)
    agent.instruct("…").execute()
# finalize() here, also on exceptions

Inheriting ​

Agent.inherit(parent, …) builds a child the way sub-agents normally look:

FlagDefaultEffect
share_workspaceTrueSame workdir and the same lazy temp dir.
share_displayTrueChild events go to the parent's display.
copy_toolboxTrueShallow copy of the registered tools.
copy_commandTrueShallow copy of slash commands.
copy_conversationFalseSub-agents start with a blank context.
span_snapshotNoneWhere to hang the child in the trace: None uses the parent's current span; a sub-agent getter passes the snapshot it was handed.

Config is deep-cloned, the API-call semaphore is shared and an already-built OpenAI client is handed over, the child's cancel_event is derived from the parent's (so cancelling the parent always cancels the child — there is no switch for it), and the child's name becomes <parent>-child-<id>.

Xun 1.5.1 (source 88942ea, 2026-11-07) documentation, generated from the source tree.