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,
    config=None,
)

Pass metadata and execution options (plugins, hooks, session_manager, agent_id, etc.) through AgentConfig, not as direct keyword arguments.

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.
configAgentConfig | NoneNoneAgent metadata and execution options. Prefer this over passing deprecated kwargs directly.

AgentConfig

python
from elsai.agent import AgentConfig

Groups agent metadata and execution options. Pass to Agent(config=...).

python
from elsai import Agent
from elsai.agent import AgentConfig

agent = Agent(
    tools=[my_tool],
    config=AgentConfig(
        agent_id="assistant",
        name="My Agent",
        plugins=[my_plugin],
        hooks=[my_hook],
        session_manager=session,
    ),
)

Fields

FieldTypeDefaultDescription
agent_idstr | NoneNone"default"Agent identifier for sessions and multi-agent.
namestr | NoneNone"elsai Agents"Human-readable agent name.
descriptionstr | NoneNoneAgent description (used in as_tool()).
stateAgentState | dict | NoneAgentState()Initial shared mutable state.
pluginslist[Plugin] | NoneNonePlugin instances.
hookslist[HookProvider | HookCallback] | NoneNoneLifecycle event hooks.
session_managerSessionManager | NoneNoneSession persistence.
structured_output_promptstr | NoneNoneDefault prompt for structured output fallback at construction time.
tool_executorToolExecutor | NoneConcurrentToolExecutor()Tool execution strategy.
retry_strategyModelRetryStrategy | NoneDefault strategyRetry on transient errors. Pass None to disable.
limitsLimits | NoneNoneDefault per-invocation budget caps for turns, output_tokens, and total_tokens. See Invocation Limits.
concurrent_invocation_modeConcurrentInvocationMode | NoneTHROWHow to handle concurrent invocations.

Deprecated kwargs

Passing agent_id, name, description, state, plugins, hooks, session_manager, structured_output_prompt, tool_executor, retry_strategy, limits, or concurrent_invocation_mode directly to Agent(...) still works but emits a DeprecationWarning and will be removed in a future release. Use AgentConfig instead.


Limits

python
from elsai.types.agent import Limits

TypedDict for per-invocation budget caps. Each set field must be a positive int.

KeyDescription
turnsMaximum agent loop iterations (model call + following tool execution)
output_tokensMaximum cumulative model output tokens in the invocation
total_tokensMaximum cumulative input + output tokens in the invocation

See Invocation Limits for semantics, validation, and stop_reason values.


Agent.__call__

python
result = agent(prompt=None, *, invocation_state=None, structured_output_model=None, structured_output_prompt=None, limits=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.
limitsLimits | NonePer-invocation budget caps. Overrides AgentConfig.limits for this call.

Returns

AgentResult


Agent.invoke_async

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

Async version of __call__. Returns AgentResult.


Agent.stream_async

python
async for event in agent.stream_async(prompt=None, *, invocation_state=None, limits=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,
    mode="reject",
)

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

ParameterDefaultDescription
nameagent.nameTool name shown to the model
descriptionagent.descriptionTool description
preserve_contextFalsePreserve conversation history between calls
mode"reject"Concurrency when the same tool is invoked in parallel: reject (fail if busy), queue (wait), or spawn (isolated worker per call)

Returns an AgentTool with a .mode property (AgentAsToolMode). Import the enum from elsai.agent:

python
from elsai.agent import AgentAsToolMode

See Agent as Tool — Concurrent invocation for usage guidance.


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" | "limit_turns" | "limit_output_tokens" | "limit_total_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.