Documentation Index
Fetch the complete documentation index at: https://docs.agentscope.io/llms.txt
Use this file to discover all available pages before exploring further.
Overview
Agent is the core abstraction in AgentScope — a stateless reasoning-acting loop engine that integrates models, tools, the permission system, human-in-the-loop, context management, middlewares, state management, and the event system into a single unified interface.
Its primary responsibilities are:
- Accepting input messages or events, invoking tools to complete tasks
- Managing context, including context compression and offloading
- Providing middleware hooks at key lifecycle stages for custom logic
- Automatically managing concurrent and sequential tool execution
Core Interfaces
The main interfaces of theAgent class are as follows:
| Method | Description |
|---|---|
reply(inputs) | Run the reasoning-acting loop and return the final Msg |
reply_stream(inputs) | Same as reply, but yields AgentEvent objects as they are produced |
observe(msgs) | Add messages to context without triggering reasoning |
compress_context(context_config) | Compress the context if token count exceeds the threshold |
Main Loop
The agent runs a reasoning-acting loop on everyreply call. The diagram below shows the main control flow.
Configure Agent
Pass parameters toAgent(...) at initialization. The examples below cover the most common setups.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
name | str | required | Agent identifier, used in messages and logs |
system_prompt | str | required | The agent’s base system prompt |
model | ChatModelBase | required | The LLM used for reasoning |
toolkit | Toolkit | None | None | Manages tools, MCP clients, skills, and tool groups |
state | AgentState | None | auto-created | Holds context, permission context, and session state |
offloader | Offloader | None | None | Offloads compressed context and tool results; must implement the Offloader protocol |
middlewares | list[MiddlewareBase] | None | None | Applied at reply, reasoning, acting, model call, and system prompt hooks |
model_config | ModelConfig | default | Retry count and fallback model |
context_config | ContextConfig | default | Context compression thresholds and tool result limits |
react_config | ReActConfig | default | Max iterations and rejection handling |
Run the Agent
Bothreply and reply_stream accept the same inputs parameter and drive the same reasoning-acting loop. The difference is in how results are delivered.
The inputs parameter accepts:
- A single
Msgor a list ofMsgobjects — starts a new reply - A
UserConfirmResultEventorExternalExecutionResultEvent— resumes from a paused state None— continue from the current state without new input
reply
reply consumes all events internally and returns the final Msg when the agent finishes or pauses for outside interaction.
reply_stream
reply_stream yields AgentEvent objects as they are produced, letting you stream text output, tool call progress, and lifecycle events to the user in real time.
observe
Useobserve to inject messages into the agent’s context without triggering a reply — useful in multi-agent setups where one agent needs to see another’s output.
Compress Context
The agent automatically compresses its context when the token count exceedscontext_config.trigger_ratio × model.context_length. Compression summarizes older messages and, if an offloader is configured, offloads them to disk.
You can also trigger compression manually:
If the system prompt alone exceeds the compression threshold,
compress_context raises a RuntimeError. Keep system prompts concise or increase the model’s context length.tool_result_limit tokens are truncated automatically. If an offloader is set, the truncated portion is offloaded and the agent receives a path reference it can read on demand.
Human-in-the-Loop
The agent pauses execution and emits special events when it encounters two situations: a tool call that requires user confirmation (permission system returns ASK), or a tool marked as external execution (the result must come from outside the agent). In both cases, you resume the agent by passing a result event back viareply.
User Confirmation
When the permission system determines a tool call needs user approval, the agent emits aRequireUserConfirmEvent and pauses.
Build the confirmation result
For each pending tool call, create a
ConfirmResult indicating whether to allow or deny it. You can also modify the tool call input or accept suggested permission rules:Resume the agent
Pass the
UserConfirmResultEvent back to reply or reply_stream:- Confirmed tool calls execute immediately and the agent continues reasoning
- Denied tool calls produce an error result visible to the LLM, which may retry with a different approach
- Accepted rules are persisted to the permission engine — matching future calls are auto-allowed without prompting again
External Tool Execution
When the agent calls a tool withis_external_tool = True, it emits a RequireExternalExecutionEvent and pauses. The tool’s logic runs outside the agent — typically by a human operator or an external system.
Execute externally and build results
Run the operation outside the agent and wrap the results as
ToolResultBlock objects:Persist Agent State
AgentState is a Pydantic model that holds everything needed to resume an agent exactly where it left off — conversation context, compression summary, permission rules, tool state, and the current reply position. Because it is a plain Pydantic model, it serialises to JSON and can be stored in any backend.
RedisStorage is the built-in storage backend. It organises state under a (user_id, agent_id, session_id) key hierarchy and exposes two focused methods for the hot path:
| Method | Description |
|---|---|
get_session(user_id, agent_id, session_id) | Load a SessionRecord whose .state field is the saved AgentState |
update_session_state(user_id, agent_id, session_id, state) | Persist the updated AgentState back to Redis after a reply |
update_session_state raises KeyError if the session does not exist yet. Use upsert_session to create the session record on the first turn, then switch to update_session_state for subsequent turns.Further Reading
Permission System
Control which tools the agent can call and under what conditions.
Middleware
Intercept and modify agent behavior at reply, reasoning, acting, and model call hooks.