AgentScope integration guide
This plugin provides AI Guardrails protection for AgentScope. By calling the Alibaba Cloud AI Guardrails service, it delivers real-time security protection for the inputs and outputs of large models and tool calls in AgentScope.
1. Core features
Scope: This topic describes the main detection points of AgentScope 1.0 and 2.0. Select the corresponding integration mechanism and interception points based on the version you use.
1.1 Detection point coverage
1.1.1 AgentScope 1.0 detection points
Reference: AgentScope 1.0 hooking functions
|
Hook name |
Trigger timing |
Function |
|
pre_reply |
Before Agent reply |
User input detection |
|
post_print |
When a streaming chunk is output |
Streaming incremental detection |
|
post_reasoning |
After LLM reasoning completes |
Final output detection + violation replacement |
|
toolkit middleware |
Before tool execution |
Tool input detection |
Call chain diagram:
User input → [pre_reply input detection] → LLM streaming reasoning → [post_print incremental detection] → [post_reasoning final detection] → Tool call → [toolkit middleware tool detection] → Return to user
1.1.2 AgentScope 1.0 Hook complete flowchart

The function of each interception point:
|
Interception point |
Trigger timing |
Input |
Interception method |
Function |
|
pre_reply |
Before Agent reply |
User message text |
Throws |
Detects user input and blocks violations directly |
|
post_print |
When each streaming chunk is output |
Accumulated text |
Marks |
Streaming incremental detection (submitted every N characters) |
|
post_reasoning |
After LLM reasoning completes |
Complete output Msg |
Replaces the output Msg |
Final detection + flush + violation replacement |
|
toolkit middleware |
Before tool execution |
Tool name + arguments |
Yields an interception message |
Blocks dangerous tool calls |
1.1.3 AgentScope 2.0 detection points
Reference: AgentScope 2.0 middleware
|
Method |
Trigger timing |
Function |
|
on_reply |
Agent reply stage |
User input detection + append warning to output |
|
on_reasoning |
LLM reasoning stage |
Streaming output incremental detection (submitted every N characters) |
|
on_acting |
Tool call stage |
Tool input detection |
Call chain diagram:
User input → [on_reply input detection] → LLM streaming reasoning → [on_reasoning incremental detection] → Tool call → [on_acting tool detection] → Return to user
1.1.4 AgentScope 2.0 Middleware complete flowchart

The function of each interception point:
|
Interception point |
Position |
Input |
Output |
Function |
|
on_reply |
Outermost layer |
User message |
Final reply |
Detects user input / appends a warning to the final output |
|
on_reasoning |
Reasoning stage |
tool_choice |
Streaming text events + Msg |
Detects model-generated text content (streaming) |
|
on_model_call |
Model API call |
messages, tools |
ChatResponse |
Intercepts the prompt sent to the model and the model's raw response |
|
on_acting |
Tool execution |
tool_call |
ToolResponse |
Detects tool call arguments and blocks dangerous operations |
|
on_system_prompt |
When building the prompt |
Current prompt string |
Transformed prompt |
Dynamically modifies the system prompt |
Note: The current guardrail middleware implements three interception points:on_reply,on_reasoning, andon_acting.on_model_callandon_system_promptare extension points reserved by the AgentScope framework and are not used in the current flow.
1.2 Intelligent interception policy
Decisions are made based on the Suggestion and RiskLevel fields returned by the guardrail service:
|
Suggestion |
RiskLevel |
Handling |
Description |
|
block |
medium/high |
Block |
Medium- and high-risk content is blocked directly |
|
block |
low |
Warn |
A warning is issued for low-risk content |
|
pass |
- |
Pass |
Safe content passes normally |
1.3 Streaming output detection
-
threshold mode: submits for detection once every time the specified number of characters is accumulated (default 300);
-
complete mode: submits for detection once after all content is accumulated;
-
Forces a flush of the remaining content when the stream ends;
-
Supports overlap retention (default 5 characters) to prevent semantic breaks at boundaries.
1.4 Chunked detection of large text
-
Content exceeding 2,000 characters is automatically chunked;
-
Calls the guardrail API concurrently (the concurrency is configurable);
-
Combines the detection results of all chunks for a final judgment;
-
Supports overlap retention (default 10 characters). Adjacent chunks overlap at the head and tail to keep the context semantically coherent.
1.5 Overlap retention mechanism
To prevent semantic loss caused by text being truncated at chunking or streaming detection boundaries, the system supports configuring the GUARDRAIL_OVERLAP_SIZE parameter:
1.5.1 Large text chunking example
Assume GUARDRAIL_MAX_CHUNK_SIZE=2000 and GUARDRAIL_OVERLAP_SIZE=10:
Input text: 5500 characters
Chunk 1: text[0:2000] ← The first chunk starts normally
Chunk 2: text[1990:3990] ← Retains 10 characters backward
Chunk 3: text[3980:5500] ← Retains 10 characters backward
1.5.2 Streaming detection example
Assume GUARDRAIL_STREAM_BUFFER_SIZE=300 and GUARDRAIL_OVERLAP_SIZE=10:
1st submission: text[0:300] ← Triggered when 300 characters are accumulated
2nd submission: text[290:590] ← Rolls back 10 characters to overlap with the previous tail
3rd submission: text[580:880] ← Rolls back another 10 characters
...
1.5.2 How it works
|
Scenario |
No overlap |
With overlap (overlap=10) |
|
Chunk boundary |
|
|
|
Streaming boundary |
1st "...how to" + 2nd "make..." → broken |
2nd "how to make..." → semantically coherent |
Configuration recommendation: The overlap value should not be too large (recommended 3 to 20, default 10). A larger value increases duplicated detection content and affects performance.
1.6 Tool call detection
Performs bidirectional security detection on tools called by the Agent (including MCP services):
-
Input detection: Concatenates the tool name and arguments into the
Tool: {name}\nArguments: {json}format for detection. Violations block execution. -
Output detection: After the tool finishes execution, extracts the
ToolResponse.contenttext for detection. Violations are replaced with an interception message.
1.7 Tracing parameter passing
Supports passing the following tracing parameters to facilitate troubleshooting and auditing:
|
Parameter |
Description |
|
request_id |
Request ID |
|
session_id |
Session ID |
|
user_id |
User ID |
|
trace_id |
Trace ID |
2. Code integration and configuration
Usage recommendation: Adjust the sample code and configuration based on your AgentScope version, project architecture, and security policy, and verify them in a test environment before deploying to production.
The project includes the basic code and test cases for integrating AI Guardrails: agentscope_guardrails.zip
|
Version |
Applicable framework |
Integration mechanism |
Directory |
|
V1 |
AgentScope 1.0 |
Hook registration |
|
|
V2 |
AgentScope 2.0 |
Middleware |
|
2.1 Project structure
├── guardrail_base.py # Base class: configuration management, service calls, response parsing
├── guardrail_service.py # Alibaba Cloud AI Guardrails API calls
├── guardrail_text_checker.py # Text checker (supports long-text chunking)
├── guardrail_stream_checker.py # Stream checker (incremental accumulation and detection)
├── v1/
│ └── guardrail_hook.py # 1.0 Hook plugin
├── v2/
│ └── guardrail_middleware.py # 2.0 Middleware
└── test/
├── guardrail_test_v1.py # 1.0 tests
└── guardrail_test_v2.py # 2.0 tests
2.2 Environment variable configuration
Create a .env file:
# Alibaba Cloud AccessKey
GUARDRAIL_AK=your_access_key_id
GUARDRAIL_SK=your_access_key_secret
# Optional configuration
GUARDRAIL_SERVICE=agent_runtime_guard
GUARDRAIL_ENDPOINT=https://green-cip.cn-shanghai.aliyuncs.com
GUARDRAIL_MAX_CHUNK_SIZE=2000
GUARDRAIL_STREAM_BUFFER_SIZE=300
GUARDRAIL_OVERLAP_SIZE=10
GUARDRAIL_STREAM_CHECK_MODE=threshold
GUARDRAIL_MAX_CONCURRENT=5
GUARDRAIL_ENABLE_TRACING=true
2.3 V1: AgentScope 1.0 integration
Register with an existing Agent through the Hook mechanism, without modifying the Agent code:
import asyncio
import agentscope
from agentscope.agent import ReActAgent
from agentscope.formatter import DashScopeChatFormatter
from agentscope.message import Msg
from agentscope.model import DashScopeChatModel
from v1.guardrail_hook import create_guardrail_hook
async def main():
agentscope.init(project="GuardrailTest", name="Test")
agent = ReActAgent(
name="TestAgent",
sys_prompt="You are a helpful assistant.",
model=DashScopeChatModel(
api_key="your-api-key",
model_name="qwen-max",
stream=True),
formatter=DashScopeChatFormatter()
)
# Create and register the guardrail Hook hook = create_guardrail_hook()
hook.register_to_agent(agent)
# Use normally; the guardrail takes effect automatically user_msg = Msg(name="user", content="Hello", role="user")
try:
response = await agent(user_msg)
print(f"Agent: {response.content}")
except ValueError as e:
print(f"Blocked: {e.args[0].content}")
asyncio.run(main())
2.4 V2: AgentScope 2.0 integration
Inject into the Agent through Middleware:
import asyncio
from agentscope.agent import Agent
from agentscope.credential import DashScopeCredential
from agentscope.formatter import DashScopeChatFormatter
from agentscope.message import Msg, TextBlock
from agentscope.model import DashScopeChatModel
from v2.guardrail_middleware import create_guardrail_middleware
async def main():
middleware = create_guardrail_middleware()
model = DashScopeChatModel(
credential=DashScopeCredential(api_key="your-api-key"),
model="qwen-max",
stream=True,
formatter=DashScopeChatFormatter(),
)
agent = Agent(
name="SafeAgent",
system_prompt="You are a helpful assistant.",
model=model,
middlewares=[middleware],
)
user_msg = Msg(
name="user",
content=[TextBlock(type="text", text="Hello")],
role="user",
)
response = await agent.reply(user_msg)
print(f"Agent: {response.get_text_content()}")
asyncio.run(main())
2.5 Run tests
# V1 testpython test/guardrail_test_v1.py
# V2 testpython test/guardrail_test_v2.py
2.5 V1 vs V2 comparison
|
Dimension |
V1 (AgentScope 1.0) |
V2 (AgentScope 2.0) |
|
Extension mechanism |
Hook (callback registration) |
Middleware (lifecycle interception) |
|
Input interception |
Throws a |
Yields a replacement message for graceful interruption |
|
Streaming handling |
|
|
|
Tool detection |
|
|
|
Integration method |
Create the Agent first, then register the Hook |
Pass |
4. Notes
Before going live, verify the interception effects on inputs, outputs, and tool calls, and continuously monitor detection results and alerts.
-
AK/SK security: Do not hard-code AK/SK in your code. We recommend using environment variables or a key management service;
-
Concurrency control: The default concurrency is 5. A higher value may cause requests to be throttled;
-
Exception handling: When a guardrail service call fails, content is passed by default. We recommend adding monitoring and alerts in production;
-
Streaming detection: The buffer size defaults to 300 characters and can be adjusted based on your business scenario;
-
Overlap retention:
GUARDRAIL_OVERLAP_SIZEdefaults to 10. We recommend setting it to 3 to 20. A larger value increases duplicated detection content and affects performance, while a smaller value makes the boundary semantic retention less effective;