Agent

Constructor parameters and methods for the Agent class.

Parameters

ParameterTypeDefaultDescription
modelOptional[Union[Model, str]]NoneModel to use for this Agent. Can be a Model object or a model string (provider:model_id)
fallback_modelsOptional[List[Union[Model, str]]]NoneModels tried in order when the primary model fails. Ignored if fallback_config is set
fallback_configOptional[FallbackConfig]NoneFallback configuration for model failures, with support for error-specific routing. Takes precedence over fallback_models
nameOptional[str]NoneAgent name
idOptional[str]NoneAgent ID (generated from name when supplied, otherwise generated automatically)
user_idOptional[str]NoneDefault user_id to use for this agent
session_idOptional[str]NoneDefault session_id to use for this agent (autogenerated if not set)
session_stateOptional[Dict[str, Any]]NoneDefault session state (stored in the database to persist across runs)
add_session_state_to_contextboolFalseSet to True to add the session_state to the context
enable_agentic_stateboolFalseSet to True to give the agent tools to update the session_state dynamically
overwrite_db_session_stateboolFalseSet to True to overwrite the session state in the database with the session state provided in the run
cache_sessionboolFalseIf True, cache the current Agent session in memory for faster access
search_past_sessionsOptional[bool]FalseAdd tools that let the agent search past sessions and read their full conversations
num_past_sessions_to_searchOptional[int]NoneMaximum number of past sessions returned by the search_past_sessions tool. Defaults to 20 when unset
num_past_session_runs_in_searchOptional[int]NoneNumber of runs included in each session preview returned by the search_past_sessions tool. Defaults to 3 when unset
dependenciesOptional[Dict[str, Any]]NoneDependencies available for tools and prompt functions
add_dependencies_to_contextboolFalseIf True, add the dependencies to the user prompt
dbOptional[Union[BaseDb, AsyncBaseDb]]NoneDatabase to use for this agent
checkpointOptional[Literal["runs", "tool-batch", "tools"]]NoneWhen to persist run state to the database. "runs" writes only at terminal states; "tool-batch" also writes after each model turn. None falls back to the AgentOS-level setting, else "runs". "tools" is currently unsupported and raises NotImplementedError
memory_managerOptional[MemoryManager]NoneMemory manager to use for this agent
enable_agentic_memoryboolFalseEnable the agent to manage memories of the user
update_memory_on_runboolFalseIf True, the agent creates/updates user memories at the end of runs
add_memories_to_contextOptional[bool]NoneIf True, add stored user memories to the system context
enable_session_summariesboolFalseIf True, the agent creates/updates session summaries at the end of runs
add_session_summary_to_contextOptional[bool]NoneIf True, the agent adds session summaries to the context
session_summary_managerOptional[SessionSummaryManager]NoneSession summary manager
compress_tool_resultsboolFalseIf True, compress tool call results to save context space
compression_managerOptional[CompressionManager]NoneCustom compression manager for compressing tool call results
offload_tool_resultsOptional[Union[bool, ResultStore]]NoneOffload long tool results. True uses the defaults, a ResultStore customizes them, None allows team inheritance, and False disables inherited offloading.
add_history_to_contextboolFalseAdd the chat history of the current session to the messages sent to the Model
num_history_runsOptional[int]NoneNumber of historical runs to include in the messages.
num_history_messagesOptional[int]NoneNumber of historical messages to include messages list sent to the Model.
knowledgeOptional[Union[KnowledgeProtocol, Callable[..., KnowledgeProtocol]]]NoneAgent Knowledge
knowledge_filtersOptional[Union[Dict[str, Any], List[FilterExpr]]]NoneKnowledge filters to apply to the knowledge base
enable_agentic_knowledge_filtersOptional[bool]NoneLet the agent choose the knowledge filters
add_knowledge_to_contextboolFalseEnable RAG by adding references from Knowledge to the user prompt
knowledge_retrieverOptional[Callable[..., Optional[List[Union[Dict, str]]]]]NoneFunction to get references to add to the user_message
references_formatLiteral["json", "yaml"]"json"Format of the references
skillsOptional[Skills]NoneSkills for this agent. Loads structured instructions, reference docs, and scripts, and gives the agent tools to access them
metadataOptional[Dict[str, Any]]NoneMetadata stored with this agent
toolsOptional[Union[List[Union[Toolkit, Callable, Function, Dict]], Callable[..., List]]]NoneA list of tools provided to the Model, or a callable factory that returns the list
tool_call_limitOptional[int]NoneMaximum number of tool calls allowed for a single run
tool_choiceOptional[Union[str, Dict[str, Any]]]NoneControls which (if any) tool is called by the model
max_tool_calls_from_historyOptional[int]NoneMaximum number of tool calls from history to keep in context. If None, all tool calls from history are included. If set to N, only the last N tool calls from history are added to the context for memory management
tool_hooksOptional[List[Callable]]NoneFunctions that will run between tool calls
pre_hooksOptional[List[Union[Callable[..., Any], BaseGuardrail, BaseEval]]]NoneFunctions called right after agent-session is loaded, before processing starts
post_hooksOptional[List[Union[Callable[..., Any], BaseGuardrail, BaseEval]]]NoneFunctions called after output is generated but before the response is returned
reasoning_modelOptional[Union[Model, str]]NoneModel to use for reasoning. Can be a Model object or a model string (provider:model_id)
reasoning_agentOptional[Agent]NoneAgent to use for reasoning
read_chat_historyboolFalseAdd a tool that allows the Model to read the chat history
search_knowledgeboolTrueAdd a tool that allows the Model to search the knowledge base
add_search_knowledge_instructionsboolTrueIf True, add instructions for using the search_knowledge tool to the system message
update_knowledgeboolFalseAdd a tool that allows the Model to update the knowledge base
read_tool_call_historyboolFalseAdd a tool that allows the Model to get the tool call history
send_media_to_modelboolTrueIf False, media (images, videos, audio, files) is only available to tools and not sent to the LLM
store_mediaboolTrueIf True, store media in the database
media_storageOptional[Union[MediaStorage, AsyncMediaStorage]]NoneOffload media to external storage and keep only a reference in the database
store_tool_messagesboolTrueIf True, store tool results in the database
store_history_messagesboolFalseIf True, store history messages in the database
system_messageOptional[Union[str, Callable, Message]]NoneProvide the system message as a string or function
system_message_rolestr"system"Role for the system message
introductionOptional[str]NoneIntroduction message for the Agent
build_contextboolTrueSet to False to skip context building
descriptionOptional[str]NoneA description of the Agent that is added to the start of the system message
instructionsOptional[Union[str, List[str], Callable]]NoneList of instructions for the agent
use_instruction_tagsboolFalseIf True, wrap the instructions in <instructions> tags in the system message
expected_outputOptional[str]NoneProvide the expected output from the Agent
additional_contextOptional[str]NoneAdditional context added to the end of the system message
markdownboolFalseIf markdown=true, add instructions to format the output using markdown
add_name_to_contextboolFalseIf True, add the agent name to the instructions
add_datetime_to_contextboolFalseIf True, add the current datetime to the instructions to give the agent a sense of time
add_location_to_contextboolFalseIf True, add the current location to the instructions to give the agent a sense of place
datetime_formatOptional[str]NoneCustom format string for the datetime added to context (e.g. "%Y-%m-%d %H:%M:%S"). If None, the default datetime string representation is used
timezone_identifierOptional[str]NoneAllows for custom timezone for datetime instructions following the TZ Database format (e.g. "Etc/UTC")
resolve_in_contextboolTrueIf True, resolve session_state, dependencies, and metadata in the user and system messages
learningOptional[Union[bool, LearningMachine]]NoneEnable learning for this agent. True creates a default LearningMachine with user profile and user memory stores; pass a LearningMachine for full control. Requires db
add_learnings_to_contextboolTrueIf True, add learnings to the system message when learning is enabled
additional_inputOptional[List[Union[str, Dict, BaseModel, Message]]]NoneA list of extra messages added after the system message and before the user message
user_message_rolestr"user"Role for the user message
build_user_contextboolTrueSet to False to skip building the user context
retriesint0Number of retries to attempt when running the Agent
delay_between_retriesint1Delay between retries (in seconds)
exponential_backoffboolFalseIf True, the delay between retries is doubled each time
input_schemaOptional[Type[BaseModel]]NoneProvide an input schema to validate the input
output_schemaOptional[Union[Type[BaseModel], Dict[str, Any]]]NoneProvide a response model to get the response as a Pydantic model or a JSON schema
parser_modelOptional[Union[Model, str]]NoneProvide a secondary model to parse the response from the primary model. Can be a Model object or a model string (provider:model_id)
parser_model_promptOptional[str]NoneProvide a prompt for the parser model
output_modelOptional[Union[Model, str]]NoneProvide an output model to structure the response from the main model. Can be a Model object or a model string (provider:model_id)
output_model_promptOptional[str]NoneProvide a prompt for the output model
parse_responseboolTrueIf True, the response from the Model is converted into the output_schema
structured_outputsOptional[bool]NoneUse model enforced structured_outputs if supported (e.g. OpenAIChat)
use_json_modeboolFalseIf output_schema is set, sets the response mode of the model, i.e. if the model should explicitly respond with a JSON object instead of a Pydantic model
save_response_to_fileOptional[str]NoneSave the response to a file
followupsboolFalseIf True, generate followup prompt suggestions after the main response and set them on RunOutput.followups
num_followupsint3Number of followup prompts to generate
followup_modelOptional[Union[Model, str]]NoneModel used to generate followups. Defaults to the agent's model
streamOptional[bool]NoneStream the response from the Agent
stream_eventsOptional[bool]NoneStream the intermediate steps from the Agent
store_eventsboolFalsePersist the events on the run response
events_to_skipOptional[List[RunEvent]]NoneSpecify which event types to skip when storing events on the RunOutput
roleOptional[str]NoneIf this Agent is part of a team, this is the role of the agent in the team
debug_modeboolFalseEnable debug logs
debug_levelLiteral[1, 2]1Debug level for logging
telemetryboolTrueLog minimal telemetry for analytics
cache_callablesboolTrueCache the results of callable tools and knowledge factories between runs
callable_tools_cache_keyOptional[Callable[..., Optional[str]]]NoneFunction that returns the cache key for the callable tools factory. Defaults to user_id or session_id from the run context
callable_knowledge_cache_keyOptional[Callable[..., Optional[str]]]NoneFunction that returns the cache key for the callable knowledge factory. Defaults to user_id or session_id from the run context

Functions

run

Run the agent.

Parameters:

  • input (Union[str, List, Dict, Message, BaseModel, List[Message]]): The input to send to the agent

  • stream (Optional[bool]): Whether to stream the response

  • stream_events (Optional[bool]): Whether to stream intermediate steps

  • user_id (Optional[str]): User ID to use

  • session_id (Optional[str]): Session ID to use

  • session_state (Optional[Dict[str, Any]]): Session state to use. By default, merged with the session state in the db.

  • run_context (Optional[RunContext]): Run context to use

  • run_id (Optional[str]): Run ID to use

  • audio (Optional[Sequence[Audio]]): Audio files to include

  • images (Optional[Sequence[Image]]): Image files to include

  • videos (Optional[Sequence[Video]]): Video files to include

  • files (Optional[Sequence[File]]): Files to include

  • knowledge_filters (Optional[Union[Dict[str, Any], List[FilterExpr]]]): Knowledge filters to apply

  • add_history_to_context (Optional[bool]): Whether to add history to context

  • add_dependencies_to_context (Optional[bool]): Whether to add dependencies to context

  • add_session_state_to_context (Optional[bool]): Whether to add session state to context

  • dependencies (Optional[Dict[str, Any]]): Dependencies to use for this run

  • metadata (Optional[Dict[str, Any]]): Metadata to use for this run

  • output_schema (Optional[Union[Type[BaseModel], Dict[str, Any]]]): Output schema to use for this run. Can be a Pydantic model or a JSON schema.

  • debug_mode (Optional[bool]): Whether to enable debug mode

  • yield_run_output (Optional[bool]): Include the final run output in a streaming iterator. Defaults to None.

Returns:

A RunOutput in non-streaming mode. Streaming yields event objects and, when yield_run_output=True, a final RunOutput.

arun

Run the agent asynchronously.

Parameters:

  • input (Union[str, List, Dict, Message, BaseModel, List[Message]]): The input to send to the agent
  • stream (Optional[bool]): Whether to stream the response
  • user_id (Optional[str]): User ID to use
  • session_id (Optional[str]): Session ID to use
  • session_state (Optional[Dict[str, Any]]): Session state to use. By default, merged with the session state in the db.
  • run_context (Optional[RunContext]): Run context to use
  • run_id (Optional[str]): Run ID to use
  • audio (Optional[Sequence[Audio]]): Audio files to include
  • images (Optional[Sequence[Image]]): Image files to include
  • videos (Optional[Sequence[Video]]): Video files to include
  • files (Optional[Sequence[File]]): Files to include
  • stream_events (Optional[bool]): Whether to stream intermediate steps
  • knowledge_filters (Optional[Union[Dict[str, Any], List[FilterExpr]]]): Knowledge filters to apply
  • add_history_to_context (Optional[bool]): Whether to add history to context
  • add_dependencies_to_context (Optional[bool]): Whether to add dependencies to context
  • add_session_state_to_context (Optional[bool]): Whether to add session state to context
  • dependencies (Optional[Dict[str, Any]]): Dependencies to use for this run
  • metadata (Optional[Dict[str, Any]]): Metadata to use for this run
  • output_schema (Optional[Union[Type[BaseModel], Dict[str, Any]]]): Output schema to use for this run. Can be a Pydantic model or a JSON schema.
  • debug_mode (Optional[bool]): Whether to enable debug mode
  • yield_run_output (Optional[bool]): Whether to yield the run output (only for streaming)
  • background (bool): Whether to run the agent in background mode. Requires a configured database. Both streaming and non-streaming modes are supported.

Returns by mode:

ModeResult
Foreground, non-streamingAwait a RunOutput
Foreground, streamingAsync iterator of events; yield_run_output=True also yields the final RunOutput
Background, non-streamingAwait a pending RunOutput for polling
Background, streamingAsync iterator of SSE-formatted strings

Direct SDK background execution is an in-process task. Durable acceptance requires the AgentOS queue path.

continue_run

Continue a run.

Parameters:

  • run_response (Optional[RunOutput]): The run response to continue
  • run_id (Optional[str]): The run ID to continue
  • requirements (Optional[List[RunRequirement]]): Updated run requirements to resolve, e.g. tool approvals
  • input (Optional[str]): Additional input to send when continuing the run
  • continue_from (Union[int, Literal["end", "last_user"]]): Where to resume the run from. Defaults to "end"
  • fork (bool): If True, continue into a new forked run instead of updating the original
  • regenerate (bool): If True, regenerate the run instead of continuing it
  • replace_original (Optional[bool]): Whether the new run replaces the original run in the session
  • additional_instructions (Optional[str]): Extra instructions added for the continued run
  • stream (Optional[bool]): Whether to stream the response
  • stream_events (Optional[bool]): Whether to stream intermediate steps
  • user_id (Optional[str]): User ID to use
  • session_id (Optional[str]): Session ID to use
  • run_context (Optional[RunContext]): Run context to use
  • knowledge_filters (Optional[Union[Dict[str, Any], List[FilterExpr]]]): Knowledge filters to apply
  • dependencies (Optional[Dict[str, Any]]): Dependencies to use for this run
  • metadata (Optional[Dict[str, Any]]): Metadata to use for this run
  • debug_mode (Optional[bool]): Whether to enable debug mode
  • yield_run_output (bool): Whether to yield the run output (only for streaming)

Returns:

  • Union[RunOutput, Iterator[Union[RunOutputEvent, RunOutput]]]: Either a RunOutput or an iterator of RunOutputEvents, depending on stream; streaming also yields the final output when yield_run_output=True

acontinue_run

Continue a run asynchronously.

Parameters:

  • run_response (Optional[RunOutput]): The run response to continue
  • run_id (Optional[str]): The run ID to continue
  • requirements (Optional[List[RunRequirement]]): Updated run requirements to resolve, e.g. tool approvals
  • input (Optional[str]): Additional input to send when continuing the run
  • continue_from (Union[int, Literal["end", "last_user"]]): Where to resume the run from. Defaults to "end"
  • fork (bool): If True, continue into a new forked run instead of updating the original
  • regenerate (bool): If True, regenerate the run instead of continuing it
  • replace_original (Optional[bool]): Whether the new run replaces the original run in the session
  • additional_instructions (Optional[str]): Extra instructions added for the continued run
  • stream (Optional[bool]): Whether to stream the response
  • stream_events (Optional[bool]): Whether to stream intermediate steps
  • user_id (Optional[str]): User ID to use
  • session_id (Optional[str]): Session ID to use
  • run_context (Optional[RunContext]): Run context to use
  • knowledge_filters (Optional[Union[Dict[str, Any], List[FilterExpr]]]): Knowledge filters to apply
  • dependencies (Optional[Dict[str, Any]]): Dependencies to use for this run
  • metadata (Optional[Dict[str, Any]]): Metadata to use for this run
  • debug_mode (Optional[bool]): Whether to enable debug mode
  • yield_run_output (bool): Whether to yield the run output (only for streaming)
  • background (bool): Use the background SSE path when stream=True; requires a database. Non-streaming continuation still runs inline

Returns:

Non-streaming execution returns a RunOutput after awaiting. Foreground streaming yields event objects and an optional final RunOutput when yield_run_output=True. Background streaming yields SSE-formatted strings.

For durable HTTP continuation, use AgentOS HITL continuations; the direct SDK method does not enqueue a durable job.

Run the agent and print the response.

Parameters:

  • input (Union[List, Dict, str, Message, BaseModel, List[Message]]): The input to send to the agent
  • session_id (Optional[str]): Session ID to use
  • session_state (Optional[Dict[str, Any]]): Session state to use. By default, merged with the session state in the db.
  • user_id (Optional[str]): User ID to use
  • run_id (Optional[str]): Run ID to use
  • audio (Optional[Sequence[Audio]]): Audio files to include
  • images (Optional[Sequence[Image]]): Image files to include
  • videos (Optional[Sequence[Video]]): Video files to include
  • files (Optional[Sequence[File]]): Files to include
  • stream (Optional[bool]): Whether to stream the response
  • markdown (Optional[bool]): Whether to format output as markdown
  • show_message (bool): Whether to show the input message
  • show_reasoning (bool): Whether to show reasoning steps
  • show_full_reasoning (bool): Whether to show full reasoning information
  • console (Optional[Any]): Console to use for output
  • tags_to_include_in_markdown (Optional[Set[str]]): Tags to include in markdown content
  • knowledge_filters (Optional[Union[Dict[str, Any], List[FilterExpr]]]): Knowledge filters to apply
  • add_history_to_context (Optional[bool]): Whether to add history to context
  • dependencies (Optional[Dict[str, Any]]): Dependencies to use for this run
  • add_dependencies_to_context (Optional[bool]): Whether to add dependencies to context
  • add_session_state_to_context (Optional[bool]): Whether to add session state to context
  • metadata (Optional[Dict[str, Any]]): Metadata to use for this run
  • debug_mode (Optional[bool]): Whether to enable debug mode

aprint_response

Run the agent and print the response asynchronously.

Parameters:

  • input (Union[List, Dict, str, Message, BaseModel, List[Message]]): The input to send to the agent
  • session_id (Optional[str]): Session ID to use
  • session_state (Optional[Dict[str, Any]]): Session state to use. By default, merged with the session state in the db.
  • user_id (Optional[str]): User ID to use
  • run_id (Optional[str]): Run ID to use
  • audio (Optional[Sequence[Audio]]): Audio files to include
  • images (Optional[Sequence[Image]]): Image files to include
  • videos (Optional[Sequence[Video]]): Video files to include
  • files (Optional[Sequence[File]]): Files to include
  • stream (Optional[bool]): Whether to stream the response
  • markdown (Optional[bool]): Whether to format output as markdown
  • show_message (bool): Whether to show the message
  • show_reasoning (bool): Whether to show reasoning
  • show_full_reasoning (bool): Whether to show full reasoning
  • console (Optional[Any]): Console to use for output
  • tags_to_include_in_markdown (Optional[Set[str]]): Tags to include in markdown content
  • knowledge_filters (Optional[Union[Dict[str, Any], List[FilterExpr]]]): Knowledge filters to apply
  • add_history_to_context (Optional[bool]): Whether to add history to context
  • add_dependencies_to_context (Optional[bool]): Whether to add dependencies to context
  • add_session_state_to_context (Optional[bool]): Whether to add session state to context
  • dependencies (Optional[Dict[str, Any]]): Dependencies to use for this run
  • metadata (Optional[Dict[str, Any]]): Metadata to use for this run
  • debug_mode (Optional[bool]): Whether to enable debug mode

cli_app

Run an interactive command-line interface to interact with the agent.

Parameters:

  • input (Optional[str]): The input to send to the agent
  • session_id (Optional[str]): Session ID to use
  • user_id (Optional[str]): User ID to use
  • user (str): Name for the user (default: "User")
  • emoji (str): Emoji for the user (default: ":sunglasses:")
  • stream (bool): Whether to stream the response (default: False)
  • markdown (bool): Whether to format output as markdown (default: False)
  • exit_on (Optional[List[str]]): List of commands to exit the CLI
  • **kwargs: Additional keyword arguments

acli_app

Run an interactive command-line interface to interact with the agent asynchronously.

Parameters:

  • input (Optional[str]): The input to send to the agent
  • session_id (Optional[str]): Session ID to use
  • user_id (Optional[str]): User ID to use
  • user (str): Name for the user (default: "User")
  • emoji (str): Emoji for the user (default: ":sunglasses:")
  • stream (bool): Whether to stream the response (default: False)
  • markdown (bool): Whether to format output as markdown (default: False)
  • exit_on (Optional[List[str]]): List of commands to exit the CLI
  • **kwargs: Additional keyword arguments

cancel_run

Cancel a run by run ID.

Parameters:

  • run_id (str): The run ID to cancel

Returns:

  • bool: True when a registered run was marked for cancellation by the default manager. Cancellation is cooperative; this is not a terminal-state acknowledgement. The default manager also records intent for an unknown run while returning False

get_run_output

Get the run output for the given run ID.

Parameters:

  • run_id (str): The run ID
  • session_id (Optional[str]): Session ID to use
  • user_id (Optional[str]): User ID to use

Returns:

  • Optional[RunOutput]: The run output

get_last_run_output

Get the last run output for the session.

Parameters:

  • session_id (Optional[str]): Session ID to use

Returns:

  • Optional[RunOutput]: The last run output

get_session

Get the session for the given session ID.

Parameters:

  • session_id (Optional[str]): Session ID to use
  • user_id (Optional[str]): User ID to use

Returns:

  • Optional[Union[AgentSession, TeamSession, WorkflowSession]]: The owning component determines the session kind

get_session_summary

Get the session summary for the given session ID.

Parameters:

  • session_id (Optional[str]): Session ID to use

Returns:

  • Session summary for the given session

get_user_memories

Get the user memories for the given user ID.

Parameters:

  • user_id (Optional[str]): User ID to use

Returns:

  • Optional[List[UserMemory]]: The user memories

aget_user_memories

Get the user memories for the given user ID asynchronously.

Parameters:

  • user_id (Optional[str]): User ID to use

Returns:

  • Optional[List[UserMemory]]: The user memories

get_session_state

Get the session state for the given session ID.

Parameters:

  • session_id (Optional[str]): Session ID to use

Returns:

  • Dict[str, Any]: The session state

update_session_state

Update the session state for the given session ID.

Parameters:

  • session_id (Optional[str]): Session ID to use
  • session_state_updates (Dict[str, Any]): The session state keys and values to update. Existing keys are overwritten; other keys are kept.

Returns:

  • Dict[str, Any]: The updated session state

get_session_metrics

Get the session metrics for the given session ID.

Parameters:

  • session_id (Optional[str]): Session ID to use

Returns:

  • Optional[SessionMetrics]: The session metrics

delete_session

Delete a session.

Parameters:

  • session_id (str): Session ID to delete
  • user_id (Optional[str]): User ID to use
  • delete_media (bool): If True, also delete the session's offloaded media from media_storage. Defaults to False

save_session

Save a session to the database.

Parameters:

  • session (Union[AgentSession, TeamSession, WorkflowSession]): The session row to save; separate run rows are not saved by this call

asave_session

Save a session to the database asynchronously.

Parameters:

  • session (Union[AgentSession, TeamSession, WorkflowSession]): The session row to save; separate run rows are not saved by this call

rename

Rename the agent and update the session.

Parameters:

  • name (str): The new name for the agent
  • session_id (Optional[str]): Session ID to use

get_session_name

Get the session name for the given session ID.

Parameters:

  • session_id (Optional[str]): Session ID to use

Returns:

  • str: The session name

set_session_name

Set the session name.

Parameters:

  • session_id (Optional[str]): Session ID to use
  • autogenerate (bool): Whether to autogenerate the name
  • session_name (Optional[str]): The name to set

Returns:

  • AgentSession: The updated session

get_session_messages

Get the messages for the given session ID.

Parameters:

  • session_id (Optional[str]): The session ID to get the messages for. If not provided, the latest used session ID is used.
  • last_n_runs (Optional[int]): The number of runs to return messages from, counting from the latest. Defaults to all runs.
  • limit (Optional[int]): The number of messages to return, counting from the latest. Defaults to all messages.
  • skip_roles (Optional[List[str]]): Skip messages with these roles.
  • skip_statuses (Optional[List[RunStatus]]): Skip messages with these statuses.
  • skip_history_messages (bool): Skip messages that were tagged as history in previous runs. Defaults to True.

Returns:

  • List[Message]: The messages for the session

get_chat_history

Get the chat history for the given session ID.

Parameters:

  • session_id (Optional[str]): The session ID to get the chat history for. If not provided, the latest used session ID is used.
  • last_n_runs (Optional[int]): The number of runs to return messages from, counting from the latest. Defaults to all runs.

Returns:

  • List[Message]: The chat history

add_tool

Add a tool to the agent.

Parameters:

  • tool (Union[Toolkit, Callable, Function, Dict]): The tool to add

set_tools

Replace the tools of the agent.

Parameters:

  • tools (Union[List[Union[Toolkit, Callable, Function, Dict]], Callable[..., List]]): The tools to set, or a callable factory that returns the list

as_tool

as_tool(name=None, description=None, title=None, annotations=None) returns a ComponentTool marker with optional MCP metadata overrides. It declares how to publish the component; creating the marker does not execute it. See MCP tools.

fork_session and afork_session

Fork the conversation into a new session with independent copied runs. Both accept keyword-only source_session_id=None and user_id=None and return the new session ID. Use the async variant with an async database.

clear_callable_cache and aclear_callable_cache

Clear cached callable results. kind=None clears all supported kinds; choose "tools" or "knowledge" to clear one kind. Set close=True to close cached resources as they are removed; the default is False.

Component persistence

MethodParametersResult
to_dict()NoneSerialized component dictionary
from_dict()data, registry=None, strict=FalseReconstructed Agent
save()Keyword-only db=None, stage="published", label=None, notes=NoneSaved version number, or None
load()id; keyword-only required db, plus registry=None, label=None, version=None, strict=False, published_only=FalseAgent or None
delete()Keyword-only db=None, hard_delete=False, require_no_dependents=TrueBoolean deletion result

Strict reconstruction raises for unresolved required component references instead of silently degrading those references. published_only=True uses the published-version pointer when neither an explicit version nor a label is supplied. require_no_dependents=True prevents deleting a component pinned by another component.

Async counterparts are available for session reads and updates, such as aget_session, aget_session_state, aupdate_session_state, and aget_run_output. Use them with asynchronous databases. acancel_run is the asynchronous cancellation request method.