ワンクリックで
optimizer
Analyzes and automatically optimizes existing agents by improving system prompts and tool configuration.
Codex または Claude でインストール この Prompt をコピーして Codex、Claude、または他のアシスタントに貼り付けると、Skill ページを確認してインストールできます。
メニュー
Analyzes and automatically optimizes existing agents by improving system prompts and tool configuration.
Codex または Claude でインストール この Prompt をコピーして Codex、Claude、または他のアシスタントに貼り付けると、Skill ページを確認してインストールできます。
SOC 職業分類に基づく
Use for framework-gated self-evolve workflows in AWorld: evolve skills, create trajectory-backed proposals, inspect self-evolve run artifacts, run aworld-cli optimize, or prepare verified apply decisions through aworld.self_evolve gates.
Draft skill generated by self-evolve for trajectory-backed task handling.
An intelligent assistant specialized in handling media files (images/audio/video). **Only for media file analysis**, does not handle document types. Media files that can be processed: - Images: .jpg, .jpeg, .png, .gif, .bmp, .webp, .svg - Audio: .mp3, .wav, .m4a, .flac, .aac, .ogg - Video: .mp4, .avi, .mov, .mkv, .webm, .flv Files that cannot be processed (please do not trigger this skill): - Documents: .pdf, .doc, .docx, .txt, .md, .rtf - Spreadsheets: .xlsx, .xls, .csv, .tsv - Presentations: .pptx, .ppt, .key - Code: .py, .js, .ts, .java, .cpp, .go, .rs - Archives: .zip, .tar, .gz, .rar, .7z - Executables: .exe, .bin, .app, .dmg - Databases: .db, .sqlite, .sql - Configuration files: .json, .xml, .yaml, .yml, .toml, .ini - Web pages: .html, .htm, .css Trigger conditions: When the user explicitly requests to analyze image/audio/video content, or when the file extension belongs to the aforementioned media types.
X (Twitter) 抓取 skill - 通过 agent-browser (CDP) 抓取指定用户推文或首页推荐流,支持关键词过滤、Tab 切换、多格式输出。使用场景:按用户/关键词抓取时间线、查看首页推荐流、生成 RSS/JSON/Markdown。
Legacy demo skill for plugin discovery tests.
Create ad-ready product video from product images, with or without character/subject images. The workflow leverages AI-powered image composition, scene understanding, and video generation. Video prompts should follow commercial shot language—visual hooks, product presence, hero shots, detail showcase, function expression, and dynamic visuals.
| name | optimizer |
| description | Analyzes and automatically optimizes existing agents by improving system prompts and tool configuration. |
| tool_names | ["AGENT_REGISTRY","CAST_ANALYSIS","CAST_CODER","CAST_SEARCH"] |
CRITICAL: READ BEFORE USE. Adherence to these rules is essential for the skill to function correctly.
Tool Calls are Direct:
CAST_ANALYSIS(...) and CAST_CODER(...) directly.from aworld.experimental.ast import ACast). The tools are pre-loaded and ready for direct invocation.CAST_ANALYSIS Query Format:
search_ast queries.
.*MyClassName.*|.*my_function_name.*search_ast queries.
"Show me the implementation of the MyClassName class"CAST_CODER Workflow:
CAST_CODER.generate_snapshot to create a backup before any modifications.search_replace or diff format text) based on your analysis. The LLM's role is to create the patch content.CAST_CODER actions (like search_replace) to apply the generated patch content to the source code.patches = [...]).Patch Content Rules:
CAST_ANALYSIS.search_ast to get accurate line numbers and context before generating a diff.The Optimizer Skill is an advanced agent capability designed to analyze and enhance other agents. It leverages Abstract Syntax Tree (AST) analysis to systematically improve an agent's behavior and performance.
It achieves this by focusing on an agent's core behavioral drivers: its system prompt (which controls its reasoning and workflow) and its tool configuration (mcp_config.py) (which defines its capabilities). By intelligently patching these high-impact areas, the Optimizer can rapidly correct flaws and expand an agent's functionality. This skill treats the target agent as a codebase, applying static analysis and automated patching to achieve its goals.
While this skill can perform any code modification, effective agent optimization primarily targets the two core behavioral drivers: The System Prompt and The Tool Configuration. Your analysis and proposed solutions must prioritize these areas.
datetime.now(ZoneInfo("Asia/Shanghai")) with datetime and ZoneInfo explicitly imported in the simple_agent.py) as the current date with the corresponding description ('Your own data is cutoff to the year 2024, so current date is xxxx, please keep in mind!') in the prompt code, to let the agent be aware of the current time.Core Principle: Always assume the problem lies in the system_prompt or mcp_config.py first. Only resort to modifying other parts of the Python code if the issue cannot be resolved through these two primary vectors (e.g., adding support for a dynamic variable in the prompt).
AGENT_REGISTRY.CAST_ANALYSIS tool to identify bottlenecks, security risks, and architectural flaws.CAST_CODER toolset.AGENT_REGISTRY to find the specified agent(s).CAST_ANALYSIS tool with the target agent's path and a precise analysis query. The tool automatically performs a multi-faceted analysis:
CAST_ANALYSIS to classify issues by severity (High, Medium, Low) and formulate an initial optimization approach.This is where you demonstrate your architectural expertise. You will deconstruct reference agents to extract their core patterns and then fuse them into a new design.
1. Foundation Analysis (search) - MANDATORY
search agent using AGENT_REGISTRY.list_desc. Once found, you MUST read both its SKILL.md (using CAST_SEARCH.read_file) using CAST_ANALYSIS.search_ast.system_prompt design, functions, the ReAct loop logic, error handling patterns, file I/O safety rules, and multi-tool coordination. This architecture is the mandatory baseline for all agents you build or modify with better quality.2. Specialist Analysis (Other Relevant Agents)
Goal: To find a specialized agent whose unique logic can be fused with the search foundation.
Action (Discovering Specialists): You must now methodically search both sources for a relevant specialist: Source 1: Built-in Agents
AGENT_REGISTRY.list_desc(source_type="built-in")
Deep Dive Analysis: Once you have selected the most relevant specialist agent, read its SKILL.md using CAST_SEARCH.read_file. You must now perform a comparative analysis against search. Ask yourself:
This analysis is critical. You must identify the unique DNA of the specialist agent to be fused into your new design.
3. Architectural Fusion: Now, you will construct the new agent's system_prompt. This is a fusion process, not a simple copy-paste.
4. Tool Configuration: Based on this fused architecture, define the final mcp_config and tool_list. It should include search's foundational tools (like terminal, search) plus any specialized tools required by the new task.
CAST_CODER.generate_snapshot with the target agent's directory to create a compressed backup (.tar.gz). This ensures a safe rollback point.CAST_CODER operations. The preferred method is search_replace for its precision and resilience to formatting differences.
MANDATORY FINAL STEP: Register the newly optimized agent to make it discoverable and usable within the current swarm.
AGENT_REGISTRYdynamic_registerlocal_agent_name: The name of the agent executing this workflow (must be "Aworld").register_agent_name: The snake_case name of the optimized agent (must match the @agent decorator).AGENT_REGISTRY.dynamic_register(local_agent_name="Aworld", register_agent_name="optimized_simple_agent")
Purpose: Discover and retrieve information about existing agents.
Actions:
query(): Search for agents by name, description, or other metadata.dynamic_register(): Register a new or modified agent into the current environment's registry, making it active.Usage: Essential for the first (Discovery) and last (Registration) steps of the workflow.
Purpose: Perform deep, AST-based static analysis of Python code.
Primary Actions:
analyze_repository(): Conduct a broad analysis of an entire agent directory to find symbols, complexities, and potential issues.search_ast(): Fetch the precise source code for specific symbols (classes, functions) or line ranges.Critical Usage Note for search_ast:
The analysis_query for this action MUST be a regular expression. Natural language queries are not supported and will fail.
user_query=".*MyClass.*|.*my_function.*"user_query="Find the MyClass class and the my_function function", user_query=".*mcp_config\\.py.", user_query=".*"Output: Returns structured JSON data containing detailed information about the code's structure, complexity, and identified issues, which serves as the foundation for the optimization strategy.
Purpose: A suite of functions for safely modifying source code files. It handles operations like creating backups and applying intelligent code replacements.
generate_snapshotCreates a compressed (.tar.gz) backup of a source directory before modifications are applied.
target_dir: The path to the directory to be backed up.search_replaceIntelligently finds and replaces a block of code in a specified file. This is the preferred method for applying patches as it is robust against minor formatting differences. It is based on aider's core matching algorithm.
Key Features:
How to Call:
The operation is defined in a JSON string passed to the operation_json parameter.
# Conceptual tool call
action_params = {
"operation_json": json.dumps({
"operation": {
"type": "search_replace",
"file_path": "path/to/your/file.py",
"search": "CODE_BLOCK_TO_FIND",
"replace": "NEW_CODE_BLOCK",
"exact_match_only": true
}
}),
"source_dir": "/path/to/agent/root", // Base directory for the operation
"show_details": True
}
CAST_CODER.search_replace(**action_params)
JSON Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
type | string | ✓ | Must be "search_replace". |
file_path | string | ✓ | The relative path to the file from source_dir. |
search | string | ✓ | This field must contain one or more complete lines of the source code. |
replace | string | ✓ | The multi-line code block to replace it with. |
exact_match_only | boolean | - | fixed as true (Optional, for documentation purposes only) |
Best Practices:
search blocks that include structural context (like def or class lines) for better accuracy.⚠️ IMPORTANT: The following code examples illustrate the standard AWorld agent structure. When generating patch content (diff format or for search_replace), you MUST ensure the resulting code adheres to these conventions to maintain compatibility and correctness within the framework. Pay close attention to imports, class definitions, decorators, and method signatures.
simple_agent.py)import os
from typing import Dict, Any, List
from aworld.agents.llm_agent import Agent
from aworld.config import AgentConfig, ModelConfig
from aworld.core.agent.swarm import Swarm
from aworld.core.common import Observation, ActionModel
from aworld.core.context.base import Context
from aworld.core.event.base import Message
# use logger to log
from aworld.logs.util import logger
from aworld.runners.hook.hook_factory import HookFactory
from aworld.runners.hook.hooks import PreLLMCallHook, PostLLMCallHook
from aworld_cli.core import agent
from aworld.sandbox import Sandbox
# The prefix simple_agent is required and must match the agent name
from simple_agent.mcp_config import mcp_config
@HookFactory.register(name="pre_simple_agent_hook")
class PreSimpleAgentHook(PreLLMCallHook):
"""Hook triggered before LLM execution. Used for monitoring, logging, etc. Should NOT modify input/output content."""
async def exec(self, message: Message, context: Context = None) -> Message:
# Important: This if-check cannot be removed and must match the current agent's name (here 'simple_agent').
# This ensures the Hook only processes messages belonging to the current agent, avoiding side effects on other agents.
if message.sender.startswith('simple_agent'):
# ⚠️ Important Note: The Message object (aworld.core.event.base.Message) is the communication carrier between agents in AWorld.
# It uses the 'payload' attribute to carry actual data, distinct from a direct 'content' attribute.
# In PreLLMCallHook, message.payload is usually an Observation object. To access content, use message.payload.content.
# Incorrect Example: message.content # ❌ AttributeError: 'Message' object has no attribute 'content'
# Correct Example: message.payload.content if hasattr(message.payload, 'content') else None # ✅
# Note: Do not modify message.payload or other input/output content here.
# Hooks should be used for:
# - Logging and monitoring
# - Counting calls and performance metrics
# - Permission checks or auditing
# - Other auxiliary functions that do not affect I/O
pass
return message
@HookFactory.register(name="post_simple_agent_hook")
class PostSimpleAgentHook(PostLLMCallHook):
"""Hook triggered after LLM execution. Used for monitoring, logging, etc. Should NOT modify input/output content."""
async def exec(self, message: Message, context: Context = None) -> Message:
# Important: This if-check cannot be removed and must match the current agent's name (here 'simple_agent').
# This ensures the Hook only processes messages belonging to the current agent.
if message.sender.startswith('simple_agent'):
# Note: Do not modify input/output content (like message.content) here.
# Hooks should be used for:
# - Logging and monitoring
# - Counting calls and performance metrics
# - Result auditing or quality checks
# - Other auxiliary functions that do not affect I/O
pass
return message
class SimpleAgent(Agent):
"""A minimal Agent implementation capable of performing basic LLM calls."""
async def async_policy(self, observation: Observation, info: Dict[str, Any] = {}, message: Message = None,
**kwargs) -> List[ActionModel]:
# Important Notes:
# 1. async_policy represents the model invocation; calling super().async_policy directly completes the LLM call.
# 2. Do not modify the observation object within async_policy; the observation should remain immutable.
# 3. Hooks (PreSimpleAgentHook and PostSimpleAgentHook) are strictly for monitoring/logging auxiliary functions
# and should never modify input/output content.
return await super().async_policy(observation, info, message, **kwargs)
@agent(
# ⚠️ CRITICAL: name MUST be lowercase words connected by underscores (snake_case)
# - ✅ CORRECT: "simple_agent", "my_custom_agent", "data_processor"
# - ❌ WRONG: "SimpleAgent", "my-agent", "MyAgent", "simpleAgent", "simple agent"
# - name should be unique and match the filename (without .py extension)
name="simple_agent",
desc="A minimal agent that can perform basic LLM calls"
)
def build_simple_swarm():
# Create Agent configuration
agent_config = AgentConfig(
llm_config=ModelConfig(
llm_model_name=os.environ.get("LLM_MODEL_NAME", "gpt-3.5-turbo"),
llm_provider=os.environ.get("LLM_PROVIDER", "openai"),
llm_api_key=os.environ.get("LLM_API_KEY"),
llm_base_url=os.environ.get("LLM_BASE_URL", "https://api.openai.com/v1"),
llm_temperature=float(os.environ.get("LLM_TEMPERATURE", "0.1")), # temperature = 0.1 is preferred, while the thus built agent is conducting coding or other serious tasks.
params={"max_completion_tokens": 40960}
)
)
# Extract all server keys from mcp_config
mcp_servers = list(mcp_config.get("mcpServers", {}).keys())
# Mandatory Use - You must use this.
sandbox = Sandbox(
mcp_config=mcp_config
)
sandbox.reuse = True
# Create SimpleAgent instance
simple_agent = SimpleAgent(
name="simple_agent",
desc="A simple AI Agent specific for basic LLM calls and tool execution",
conf=agent_config,
# Note: If the Agent needs to read/write files, remind the agent in the system_prompt to use absolute paths.
# Relative paths should be avoided. Use os.path.abspath() or Path(__file__).parent to resolve paths.
system_prompt="""You are an all-capable AI assistant aimed at solving any task presented by the user.
<the following instructions, workflows, guardrails should be adapt to the user's requirements and referred SKILL.md>
""",
mcp_servers=mcp_servers,
mcp_config=mcp_config,
sandbox=sandbox
)
# Return the Swarm containing this Agent
return Swarm(simple_agent)
mcp_config.py)mcp_config = {
"mcpServers": {
"csv": {
"command": "python",
"args": [
"-m",
"examples.gaia.mcp_collections.documents.mscsv"
],
"env": {
},
"client_session_timeout_seconds": 9999.0
},
"docx": {
"command": "python",
"args": [
"-m",
"examples.gaia.mcp_collections.documents.msdocx"
],
"env": {
},
"client_session_timeout_seconds": 9999.0
},
"download": {
"command": "python",
"args": [
"-m",
"examples.gaia.mcp_collections.tools.download"
],
"env": {
},
"client_session_timeout_seconds": 9999.0
},
"xlsx": {
"command": "python",
"args": [
"-m",
"examples.gaia.mcp_collections.documents.msxlsx"
],
"env": {
},
"client_session_timeout_seconds": 9999.0
},
"image": {
"command": "python",
"args": [
"-m",
"examples.gaia.mcp_collections.media.image"
],
"env": {
},
"client_session_timeout_seconds": 9999.0
},
"pdf": {
"command": "python",
"args": [
"-m",
"examples.gaia.mcp_collections.documents.pdf"
],
"env": {
},
"client_session_timeout_seconds": 9999.0
},
"pptx": {
"command": "python",
"args": [
"-m",
"examples.gaia.mcp_collections.documents.mspptx"
],
"env": {
},
"client_session_timeout_seconds": 9999.0
},
"search": {
"command": "python",
"args": [
"-m",
"examples.gaia.mcp_collections.tools.search"
],
"env": {
"GOOGLE_API_KEY": "${GOOGLE_API_KEY}",
"GOOGLE_CSE_ID": "${GOOGLE_CSE_ID}"
},
"client_session_timeout_seconds": 9999.0
},
"terminal": {
"command": "python",
"args": [
"-m",
"examples.gaia.mcp_collections.tools.terminal"
]
},
"txt": {
"command": "python",
"args": [
"-m",
"examples.gaia.mcp_collections.documents.txt"
],
"env": {
},
"client_session_timeout_seconds": 9999.0
},
"ms-playwright": {
"command": "npx",
"args": [
"@playwright/mcp@latest",
"--no-sandbox",
"--isolated",
"--output-dir=/tmp/playwright",
"--timeout-action=10000",
],
"env": {
"PLAYWRIGHT_TIMEOUT": "120000",
"SESSION_REQUEST_CONNECT_TIMEOUT": "120"
}
}
}
}