Skip to content

Agent

python
from elsai import Agent

The core class for interacting with LLMs and tools.


Agent.__init__

python
Agent(
    model=None,
    messages=None,
    tools=None,
    system_prompt=None,
    structured_output_model=None,
    callback_handler=<default>,
    conversation_manager=None,
    record_direct_tool_call=True,
    load_tools_from_directory=False,
    trace_attributes=None,
    *,
    agent_id=None,
    name=None,
    description=None,
    state=None,
    plugins=None,
    hooks=None,
    session_manager=None,
    structured_output_prompt=None,
    tool_executor=None,
    retry_strategy=<default>,
    concurrent_invocation_mode=ConcurrentInvocationMode.THROW,
)

Parameters

NameTypeDefaultDescription
modelModel | str | NoneBedrockModel()LLM provider. Pass a Model instance, a Bedrock model ID string, or None for the default.
messageslist[Message] | None[]Pre-loaded conversation history.
toolslist | NoneNoneTools available to the agent.
system_promptstr | list[SystemContentBlock] | NoneNoneSystem instructions.
structured_output_modeltype[BaseModel] | NoneNonePydantic model for typed responses.
callback_handlerCallable | NonePrintingCallbackHandler()Event callback. Pass None for silent operation.
conversation_managerConversationManager | NoneSlidingWindowConversationManager()History management strategy.
record_direct_tool_callboolTrueRecord direct agent.tool.* calls in message history.
load_tools_from_directoryboolFalseAuto-load tools from ./tools/ with hot-reload.
trace_attributesMapping[str, AttributeValue] | NoneNoneCustom OpenTelemetry span attributes.
agent_idstr | None"default"Agent identifier for sessions and multi-agent.
namestr | None"Elsai Agents"Human-readable agent name.
descriptionstr | NoneNoneAgent description (used in as_tool()).
stateAgentState | dict | NoneAgentState()Shared mutable state.
pluginslist[Plugin] | NoneNonePlugin instances.
hookslist[HookProvider | HookCallback] | NoneNoneLifecycle event hooks.
session_managerSessionManager | NoneNoneSession persistence.
structured_output_promptstr | NoneNoneCustom prompt for structured output fallback.
tool_executorToolExecutor | NoneConcurrentToolExecutor()Tool execution strategy.
retry_strategyModelRetryStrategy | NoneDefault strategyRetry on transient errors.
concurrent_invocation_modeConcurrentInvocationModeTHROWHow to handle concurrent invocations.

Agent.__call__

python
result = agent(prompt=None, *, invocation_state=None, structured_output_model=None, structured_output_prompt=None)

Process input through the agent loop synchronously.

Parameters

NameTypeDescription
promptstr | list[ContentBlock] | list[Message] | NoneUser input.
invocation_statedict | NoneExtra state passed through the event loop.
structured_output_modeltype[BaseModel] | NoneOverride structured output model for this call.
structured_output_promptstr | NoneOverride structured output prompt for this call.

Returns

AgentResult


Agent.invoke_async

python
result = await agent.invoke_async(prompt=None, *, invocation_state=None, structured_output_model=None)

Async version of __call__. Returns AgentResult.


Agent.stream_async

python
async for event in agent.stream_async(prompt=None, *, invocation_state=None):
    ...

Async iterator that yields event dicts as the agent runs.

Event keys

KeyTypeDescription
datastrText chunk being generated
completeboolTrue when text generation is done
current_tool_usedictTool call in progress (name, input)
resultAgentResultFinal result (last event)

Agent.cancel

python
agent.cancel()

Thread-safe cancellation. The agent stops at the next checkpoint and returns stop_reason="cancelled".


Agent.add_hook

python
agent.add_hook(callback, event_type=None)

Register a hook callback. Event type is inferred from the callback's type hint if not specified.


Agent.as_tool

python
tool = agent.as_tool(*, name=None, description=None, preserve_context=False)

Wrap this agent as a tool for use by another agent.


Agent.take_snapshot

python
snapshot = agent.take_snapshot(*, preset=None, include=None, exclude=None, app_data=None)

Capture current agent state as a Snapshot.


Agent.load_snapshot

python
agent.load_snapshot(snapshot)

Restore agent state from a Snapshot.


Agent.cleanup

python
agent.cleanup()

Release resources (MCP connections, file watchers). Called automatically on garbage collection.


Properties

PropertyTypeDescription
system_promptstr | NoneCurrent system prompt as string
system_prompt_contentlist[SystemContentBlock] | NoneSystem prompt as content blocks
tool_ToolCallerDirect tool invocation interface (agent.tool.tool_name(...))
tool_nameslist[str]Names of all registered tools
messageslist[Message]Current conversation history
stateAgentStateAgent state store
modelModelThe model instance

AgentResult

python
result = agent("Hello")

result.message        # dict: the final assistant message
result.stop_reason    # str: "end_turn" | "max_tokens" | "tool_use" | "cancelled"
result.metrics        # Metrics: token counts and latency
result.state          # dict: agent state at completion
result.structured_output  # BaseModel | None: parsed structured output

@tool decorator

python
from elsai import tool

@tool
def my_tool(param: str) -> str:
    """Tool description.

    Args:
        param: Parameter description.
    """
    return result

Transforms a Python function into an agent tool. The function's name, docstring, and type hints define the tool's schema.

Copyright © 2026 Elsai Foundry.