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.
identifieruuidStable 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.
api_call_semaphoreSemaphore(8)Shared with sub-agents to cap concurrent model calls (DEFAULT_API_CALL_CONCURRENCY).
extension_loaderdefault_loaderScanner for $XUN_HOME/extensions/.

The first group (config, workspace, toolbox, command, display, extension_loader) is what Agent.inherit() copies or shares; 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.

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, and a weakref.finalize hook catches agents you forgot about:

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.
inherit_cancel_eventTrueCancelling the parent cancels the child.

Config is deep-cloned, the API-call semaphore is shared, and the child's name becomes <parent>-child-<id>.

Xun 1.4.2dev (unreleased; source 51d23f3, 2026-10-16) documentation, generated from the source tree.