ai-agent-book 精选快照(<2MB 代码与文档,来自 github.com/bojieli/ai-agent-book)
Build latest book artifacts / build (push) Canceled after 0s
dependency resolution / resolve (3.11) (push) Canceled after 0s
dependency resolution / resolve (3.13) (push) Canceled after 0s
deploy-pages / build (push) Canceled after 0s
deploy-pages / deploy (push) Canceled after 0s
i18n consistency check / check (push) Canceled after 0s
provider adoption tests / test (chapter2/context-compression) (push) Canceled after 0s
provider adoption tests / test (chapter2/prompt-injection) (push) Canceled after 0s
provider adoption tests / test (chapter2/system-hint) (push) Canceled after 0s
provider adoption tests / test (chapter3/log-sanitization) (push) Canceled after 0s
web-search-agent tests / test (push) Canceled after 0s
web-search-agent tests / agentbook (push) Canceled after 0s

This commit is contained in:
2026-08-20 13:12:50 +00:00
commit b119135836
10275 changed files with 3284984 additions and 0 deletions
@@ -0,0 +1,42 @@
import logging
from typing import Any, Dict, List
from aworld.agents.llm_agent import Agent
from aworld.core.common import Observation, ActionModel, ActionResult
from aworld.core.context.base import Context
from aworld.core.event.base import Message
class PlaywrightAgent(Agent):
def __int__(self, **kwargs):
super().__init__(name="playwright_agent", **kwargs)
async def async_policy(self, observation: Observation, info: Dict[str, Any] = {}, message: Message = None,
**kwargs) -> List[ActionModel]:
return await super().async_policy(observation, info, message, **kwargs)
async def _add_tool_result_to_memory(self, tool_call_id: str, tool_result: ActionResult, context: Context):
"""Add tool result to memory"""
logging.info(f"tool_result: {tool_result}")
if isinstance(tool_result.content, str) and tool_result.content.startswith("data:image"):
image_content = tool_result.content
tool_result.content = "this picture is below "
await super()._add_tool_result_to_memory(tool_call_id, tool_result, context)
image_content = [
{
"type": "text",
"text": f"this is file of tool_call_id:{tool_result.tool_call_id}"
},
{
"type": "image_url",
"image_url": {
"url": image_content
}
}
]
await super()._add_human_input_to_memory(image_content, context)
else:
await super()._add_tool_result_to_memory(tool_call_id, tool_result, context)
@@ -0,0 +1,259 @@
import logging
import os
from datetime import datetime
from typing import List, Dict, Any, Optional, AsyncGenerator
from aworld.logs.util import logger
from aworld.output.ui.markdown_aworld_ui import MarkdownAworldUI
from aworld.agents.llm_agent import Agent
from aworld.config import AgentConfig, TaskConfig
from aworld.core.common import ActionModel, Observation
from aworld.core.context.base import Context
from aworld.core.event.base import Message
from aworld.core.memory import LongTermConfig, MemoryItem, AgentMemoryConfig
from aworld.core.task import Task
from aworld.memory.main import MemoryFactory
from aworld.memory.models import LongTermMemoryTriggerParams, MemoryAIMessage, MessageMetadata, UserProfile, \
MemoryHumanMessage
from aworld.memory.utils import build_history_context
from aworld.output import AworldUI
from aworld.output.utils import load_workspace
from aworld.prompt import Prompt
from aworld.runner import Runners
from aworld.utils.common import load_mcp_config
from tests.memory.prompts import SELF_EVOLVING_USER_INPUT_REWRITE_PROMPT, RESEARCH_PROMPT
class SuperAgent:
"""
Super agent
"""
def __init__(self, id: str, name: str, **kwargs):
self.memory_config = AgentMemoryConfig(
enable_long_term=True,
long_term_config=LongTermConfig.create_simple_config(
enable_user_profiles=True
)
)
self.memory = MemoryFactory.instance()
agent_config = AgentConfig(
llm_provider="openai",
llm_model_name=os.environ["LLM_MODEL_NAME"],
llm_api_key=os.environ["LLM_API_KEY"],
llm_base_url=os.environ["LLM_BASE_URL"]
)
self.sub_agent = SelfEvolvingAgent(
conf=agent_config,
agent_id="self_evolving_agent",
name="self_evolving_agent",
system_prompt=RESEARCH_PROMPT,
mcp_servers=["ms-playwright","google-search","tavily-mcp", "filesystem"],
history_messages=100,
mcp_config=load_mcp_config(),
agent_memory_config=AgentMemoryConfig(
enable_summary=True,
summary_rounds=10,
summary_model=os.environ["LLM_MODEL_NAME"],
enable_long_term=True,
long_term_config=LongTermConfig.create_simple_config(
enable_agent_experiences=True
)
)
)
self.id = id
self.name = name
async def async_run(self, user_id, session_id, task_id, user_input):
"""
Run task
"""
task_context = await self.get_history_context(user_id, session_id, task_id, user_input)
await self.add_human_input(user_id, session_id, task_id, user_input)
result = await self.run_task(user_id, session_id, task_id, user_input, task_context)
await self.add_ai_message(user_id, session_id, task_id, result)
await self.post_run(user_id, session_id, task_id, task_context)
async def run_task(self, user_id, session_id, task_id, user_input, task_context):
user_input = await self.rewrite_user_input(user_id, user_input, task_context)
task = Task(
id=task_id,
session_id=session_id,
user_id=user_id,
input=user_input,
agent=self.sub_agent,
conf=TaskConfig(),
context=task_context
)
logging.info(f"[SuperAgent] run task start, task_id = {task.id} input = {input}")
result = ""
session_workspace = await load_workspace(workspace_id=task.session_id, workspace_type="local",
workspace_parent_path="data/workspaces")
local_ui = MarkdownAworldUI(
session_id=task.session_id,
task_id=task.id,
workspace=session_workspace
)
# get outputs
outputs = Runners.streamed_run_task(task)
with open(f"output_{task.session_id}.md", "a") as f:
# render output
try:
f.write(f"User: {user_input}")
async for output in outputs.stream_events():
res = await AworldUI.parse_output(output, local_ui)
if res:
if isinstance(res, AsyncGenerator):
async for item in res:
result += item
f.write(item)
else:
result += res
f.write(res)
except Exception as e:
logger.error(f"Error: {e}")
finally:
f.close()
logging.info(f"[SuperAgent] run task finished, task_id = {task.id} result = {result}")
return result
async def rewrite_user_input(self, user_id, user_input, task_context):
"""
Rewrite user input
"""
user_profiles = await self.retrival_user_profile(user_id, user_input)
logging.info(f"[SuperAgent] rewrite_user_input user_profiles = {user_profiles}")
similar_messages_history = await self.retrival_similar_messages_history(user_id, user_input)
logging.info(f"[SuperAgent] rewrite_user_input similar_messages_history = {similar_messages_history}")
return SELF_EVOLVING_USER_INPUT_REWRITE_PROMPT.format(user_input=user_input, user_profiles=user_profiles,
similar_messages_history=similar_messages_history)
async def get_history_context(self, user_id, session_id, task_id, user_input):
# get cur session history
history_messages = self.memory.get_last_n(10, filters={
"user_id": user_id,
"session_id": session_id,
"agent_id": self.id
})
task_context = Context()
task_context.context_info["history"] = build_history_context(history_messages)
# get cur user profile
user_profiles = await self.retrival_user_profile(user_id, user_input)
task_context.context_info["user_profiles"] = user_profiles
# get similar messages_history
similar_messages_history = await self.retrival_similar_messages_history(user_id, user_input)
task_context.context_info["similar_messages_history"] = similar_messages_history
return task_context
async def post_run(self, user_id, session_id, task_id, task_context):
"""
Post run
"""
logging.info(f"[SuperAgent] post_run user_id = {user_id}, session_id = {session_id}, task_id = {task_id}")
await self.extract_user_profile(user_id, session_id, task_id)
await self.sub_agent.evolving(user_id, session_id, task_id)
async def add_ai_message(self, user_id, session_id, task_id, result):
await self.memory.add(MemoryAIMessage(
content=result,
metadata=MessageMetadata(
user_id=user_id,
session_id=session_id,
task_id=task_id,
agent_id=self.id,
agent_name=self.name
)
), agent_memory_config=self.memory_config)
async def add_human_input(self, user_id, session_id, task_id, user_input):
await self.memory.add(MemoryHumanMessage(
content=user_input,
metadata=MessageMetadata(
user_id=user_id,
session_id=session_id,
task_id=task_id,
agent_id=self.id,
agent_name=self.name
)
), agent_memory_config=self.memory_config)
async def extract_user_profile(self, user_id, session_id, task_id):
await self.memory.trigger_short_term_memory_to_long_term(LongTermMemoryTriggerParams(
agent_id=self.id,
session_id=session_id,
task_id=task_id,
user_id=user_id,
force=True
), self.memory_config)
async def gen_long_term_memory(self, user_id, session_id, task_id):
"""
Gen long-term memory
"""
await self.memory.trigger_short_term_memory_to_long_term(LongTermMemoryTriggerParams(
agent_id=self.id,
session_id=session_id,
task_id=task_id,
user_id=user_id
), self.memory_config)
async def retrival_user_profile(self, user_id, user_input) -> Optional[list[UserProfile]]:
"""
Retrieve similar user profiles from long-term storage for context.
"""
return await self.memory.retrival_user_profile(user_id, user_input)
async def retrival_similar_messages_history(self, user_id, user_input) -> Optional[List[MemoryItem]]:
"""
Retrieve similar messages history from long-term storage for context.
"""
return await self.memory.retrival_similar_user_messages_history(user_id, user_input)
class SelfEvolvingAgent(Agent):
"""
Self-evolving agent
"""
async def async_policy(self, observation: Observation, info: Dict[str, Any] = {}, message: Message = None,
**kwargs) -> List[ActionModel]:
return await super().async_policy(observation, info, message, **kwargs)
async def evolving(self, user_id, session_id, task_id):
"""
Evolving agent experience
"""
logging.info(
f"[SelfEvolvingAgent] evolving_agent_experience user_id = {user_id}, session_id = {session_id}, task_id = {task_id}")
await self.memory.trigger_short_term_memory_to_long_term(LongTermMemoryTriggerParams(
agent_id=self.id(),
session_id=session_id,
task_id=task_id,
user_id=user_id,
force=True
), self.memory_config)
async def custom_system_prompt(self, context: Context, content: str):
"""
custom it
"""
agent_experiences = await self.memory.retrival_agent_experience(self.id(), context.get_task().input)
logging.info(f"[SelfEvolvingAgent] custom_system_prompt agent_experiences = {agent_experiences}")
return Prompt(self.system_prompt).get_prompt(variables={
"history": context.context_info.get("history", ""),
"agent_experiences": agent_experiences,
"cur_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
})
@@ -0,0 +1,95 @@
import asyncio
import logging
import os
from dotenv import load_dotenv
from aworld.core.memory import LongTermConfig, MemoryConfig, AgentMemoryConfig, EmbeddingsConfig, VectorDBConfig, \
MemoryLLMConfig
from aworld.memory.main import MemoryFactory
from aworld.memory.models import LongTermMemoryTriggerParams, MessageMetadata
from tests.memory.short_term.utils import add_mock_messages
async def init():
load_dotenv()
MemoryFactory.init(
config=MemoryConfig(
provider="aworld",
llm_config=MemoryLLMConfig(
provider="openai",
model_name=os.environ["LLM_MODEL_NAME"],
api_key=os.environ["LLM_API_KEY"],
base_url=os.environ["LLM_BASE_URL"]
),
embedding_config=EmbeddingsConfig(
provider="ollama",
base_url="http://localhost:11434",
model_name="nomic-embed-text"
),
vector_store_config=VectorDBConfig(
provider="chroma",
config=
{
"chroma_data_path": "./chroma_db",
"collection_name": "aworld",
}
)
))
async def trigger_long_term_memory_agent_experience():
await init()
memory = MemoryFactory.instance()
metadata = MessageMetadata(
user_id="zues",
session_id="session#foo",
task_id="zues:session#foo:task#1",
agent_id="super_agent",
agent_name="super_agent"
)
await add_mock_messages(memory, metadata)
memory_config = AgentMemoryConfig(
enable_long_term=True,
long_term_config=LongTermConfig.create_simple_config(
enable_agent_experiences=True
)
)
await memory.trigger_short_term_memory_to_long_term(LongTermMemoryTriggerParams(
agent_id=metadata.agent_id,
session_id=metadata.session_id,
task_id=metadata.task_id,
user_id=metadata.user_id,
force=True
), memory_config)
"""
"""
await asyncio.sleep(10)
async def query_agent_experience():
# await init()
memory = MemoryFactory.instance()
metadata = MessageMetadata(
user_id="zues",
session_id="session#foo",
task_id="zues:session#foo:task#1",
agent_id="super_agent",
agent_name="super_agent"
)
agent_experiences = await memory.retrival_agent_experience(
agent_id=metadata.agent_id,
user_input="what is my advantage skills?"
)
for agent_experience in agent_experiences:
logging.info(f"Search->{agent_experience}")
# if __name__ == '__main__':
# asyncio.run(trigger_long_term_memory_agent_experience())
# asyncio.run(query_agent_experience())
@@ -0,0 +1,107 @@
import asyncio
import logging
import os
from dotenv import load_dotenv
from aworld.core.memory import LongTermConfig, MemoryConfig, AgentMemoryConfig, MemoryLLMConfig, EmbeddingsConfig, \
VectorDBConfig
from aworld.memory.main import MemoryFactory
from aworld.memory.models import LongTermMemoryTriggerParams, MessageMetadata
from tests.memory.short_term.utils import add_mock_messages
async def init():
load_dotenv()
MemoryFactory.init(
config=MemoryConfig(
provider="aworld",
llm_config=MemoryLLMConfig(
provider="openai",
model_name=os.environ["LLM_MODEL_NAME"],
api_key=os.environ["LLM_API_KEY"],
base_url=os.environ["LLM_BASE_URL"]
),
embedding_config=EmbeddingsConfig(
provider="ollama",
base_url="http://localhost:11434",
model_name="nomic-embed-text"
),
vector_store_config=VectorDBConfig(
provider="chroma",
config=
{
"chroma_data_path": "./chroma_db",
"collection_name": "aworld",
}
)
))
async def trigger_long_term_memory_user_profile():
await init()
memory = MemoryFactory.instance()
metadata = MessageMetadata(
user_id="zues",
session_id="session#foo",
task_id="zues:session#foo:task#1",
agent_id="super_agent",
agent_name="super_agent"
)
await add_mock_messages(memory, metadata)
memory_config = AgentMemoryConfig(
enable_long_term=True,
long_term_config=LongTermConfig.create_simple_config(
enable_user_profiles=True
)
)
await memory.trigger_short_term_memory_to_long_term(LongTermMemoryTriggerParams(
agent_id=metadata.agent_id,
session_id=metadata.session_id,
task_id=metadata.task_id,
user_id=metadata.user_id,
force=True
), memory_config)
"""
[
{
"key": "skills.technical",
"value": {
"gaming_skills": ["League of Legends"]
}
},
{
"key": "goals.learning",
"value": {
"target": "improve gaming skills in League of Legends"
}
}
]
"""
await asyncio.sleep(10)
async def query_user_profile():
memory = MemoryFactory.instance()
metadata = MessageMetadata(
user_id="zues",
session_id="session#foo",
task_id="zues:session#foo:task#1",
agent_id="super_agent",
agent_name="super_agent"
)
user_profiles = await memory.retrival_user_profile(
user_id=metadata.user_id,
user_input="what is my advantage skills?"
)
for user_profile in user_profiles:
logging.info(f"Search->{user_profile}")
# if __name__ == '__main__':
# asyncio.run(trigger_long_term_memory_user_profile())
# asyncio.run(query_user_profile())
@@ -0,0 +1,98 @@
# coding: utf-8
# Copyright (c) 2025 inclusionAI.
import asyncio
from dotenv import load_dotenv
from aworld.memory.main import MemoryFactory
from tests.memory.agent.self_evolving_agent import SuperAgent
async def _run_multi_session_examples() -> None:
"""
Run examples across multiple sessions demonstrating a complete learning workflow.
This example shows a deep learning process about Agent-RL (Reinforcement Learning Agents):
1. Deep search and research on Agent-RL concepts and implementations
2. Content revision and modification for specific aspects
3. Text-to-speech conversion for learning materials
4. Next-day review and reinforcement
"""
# await init_dataset()
super_agent = SuperAgent(id="super_agent", name="super_agent")
user_id = "alice"
# Day 1 - Session 1: Deep Search on Agent-RL
session_id = "day1_morning_session"
await super_agent.async_run(
user_id=user_id,
session_id=session_id,
task_id="alice:day1_morning:task#1",
user_input="我想深入了解基于强化学习的智能体(Agent-RL)。请使用DEEPSEARCH帮我研究这个话题,包括:1. 基础架构(状态空间、动作空间、奖励机制)2. 常用算法(DQN、PPO、SAC等)3. 环境交互设计 4. 实现最佳实践"
)
await super_agent.async_run(
user_id=user_id,
session_id=session_id,
task_id="alice:day1_morning:task#2",
user_input="基于上面的搜索结果,请生成一个结构化的学习文档(markdown),重点包含:1. 理论框架 2. 代码示例(使用Python实现简单的Agent-RL)3. 常见问题和解决方案"
)
# Day 1 - Session 2: Content Revision
# session_id = "day1_afternoon_session"
# await super_agent.async_run(
# user_id=user_id,
# session_id=session_id,
# task_id="alice:day1_afternoon:task#1",
# user_input="我觉得之前生成的文档中'环境交互设计'这部分需要补充。特别是:1. 如何设计合适的奖励函数 2. 环境状态的表示方法 3. 动作空间的设计考虑"
# )
# await super_agent.async_run(
# user_id=user_id,
# session_id=session_id,
# task_id="alice:day1_afternoon:task#2",
# user_input="太好了!现在请帮我把修改后的文档转换成更容易理解的形式,特别是把强化学习的数学概念用通俗的例子解释,准备生成语音内容"
# )
# Day 1 - Session 3: TTS Generation
# session_id = "day1_evening_session"
# await super_agent.async_run(
# user_id=user_id,
# session_id=session_id,
# task_id="alice:day1_evening:task#1",
# user_input="请将内容转换成语音文件,要求:1. 语速适中 2. 关键算法和数学概念讲解要清晰 3. 按照'理论基础-算法实现-实践应用'的顺序分章节 4. 生成字幕"
# )
# await super_agent.async_run(
# user_id=user_id,
# session_id=session_id,
# task_id="alice:day1_evening:task#2",
# user_input="请生成一个Agent-RL的知识图谱,包含:1. 核心概念关系 2. 算法分类 3. 应用场景 4. 学习路径建议"
# )
# Day 2 - Morning Review
# session_id = "day2_morning_session"
# await super_agent.async_run(
# user_id=user_id,
# session_id=session_id,
# task_id="alice:day2_morning:task#1",
# user_input="早上好!请帮我回顾一下昨天关于Agent-RL的学习内容。特别是:1. 通过知识图谱回顾核心概念 2. 复习各个算法的优缺点 3. 检查是否理解了关键的数学原理"
# )
# await super_agent.async_run(
# user_id=user_id,
# session_id=session_id,
# task_id="alice:day2_morning:task#2",
# user_input="基于已学内容,请推荐下一步的学习方向:1. 进阶算法(如MARL多智能体强化学习)2. 实际项目实践 3. 前沿研究方向"
# )
# await super_agent.async_run(
# user_id=user_id,
# session_id=session_id,
# task_id="alice:day2_morning:task#3",
# user_input="请设计一个实践项目,让我可以应用学到的Agent-RL知识。要求:1. 项目难度适中 2. 包含完整的代码框架 3. 有清晰的评估指标 4. 提供优化建议"
# )
# if __name__ == '__main__':
# load_dotenv()
#
# MemoryFactory.init()
#
# # Run the multi-session example with concrete learning tasks
# asyncio.run(_run_multi_session_examples())
@@ -0,0 +1,140 @@
# coding: utf-8
# Copyright (c) 2025 inclusionAI.
import asyncio
from asyncio.log import logger
from datetime import datetime
from dotenv import load_dotenv
from tests.memory.agent.self_evolving_agent import SuperAgent
from tests.memory.utils import init_postgres_memory
async def _run_single_session_examples() -> None:
"""
Run examples within a single session.
Demonstrates a complete learning session about reinforcement learning concepts.
"""
# await init_dataset()
salt = datetime.now().strftime("%Y%m%d%H%M%S")
super_agent = SuperAgent(id="super_agent", name="super_agent")
user_id = "zues"
session_id = f"session#foo_{salt}"
logger.info(f"🚀 Running session {session_id}")
# Task 1: Research on Mem0
user_input_1 = """Conduct a comprehensive analysis of the Mem0 memory system (Part 1 of 4):
Research Focus Areas:
- System Overview and Core Principles
- Architectural Design and Implementation
- Key Features and Capabilities
- Use Cases and Applications
- Integration Patterns
- Performance Characteristics
Requirements:
- Utilize authoritative sources (GitHub, arXiv, etc.)
- Include code examples and implementation details
- Analyze real-world applications
- Format as a well-structured Markdown report
- Prepare for comparison with other memory systems in subsequent analysis
"""
# Task 2: Research on MemoryBank
user_input_2 = """Conduct a comprehensive analysis of the MemoryBank system (Part 2 of 4):
Research Focus Areas:
- System Overview and Core Principles
- Architectural Design and Implementation
- Key Features and Capabilities
- Use Cases and Applications
- Integration Patterns
- Performance Characteristics
- Comparative Analysis with Mem0
Requirements:
- Build upon previous Mem0 analysis
- Focus on unique features and differentiators
- Include practical implementation examples
- Document integration capabilities
- Format as a well-structured Markdown report
"""
# Task 3: Research on MemoryOS
user_input_3 = """Conduct a comprehensive analysis of the MemoryOS system (Part 3 of 4):
Research Focus Areas:
- System Overview and Core Principles
- Architectural Design and Implementation
- Key Features and Capabilities
- Use Cases and Applications
- Integration Patterns
- Performance Characteristics
- Comparative Analysis with Mem0 and MemoryBank
Requirements:
- Build upon previous analyses
- Highlight unique operating system integration aspects
- Include practical implementation examples
- Analyze scalability and performance
- Format as a well-structured Markdown report
"""
# Task 4: Research on MemoryAgent
user_input_4 = """Conduct a comprehensive analysis of the MemoryAgent system (Part 4 of 4):
Research Focus Areas:
- System Overview and Core Principles
- Architectural Design and Implementation
- Key Features and Capabilities
- Use Cases and Applications
- Integration Patterns
- Performance Characteristics
- Comprehensive Comparative Analysis
- Future Development Trends
Requirements:
- Synthesize findings from all previous analyses
- Create a comparative matrix of all systems
- Identify best practices and recommendations
- Discuss future trends and potential improvements
- Format as a well-structured Markdown report
"""
# Execute tasks sequentially
await super_agent.async_run(user_id=user_id, session_id=session_id, task_id=f"zues:session#foo:task#1_{salt}",
user_input=user_input_1)
await super_agent.async_run(user_id=user_id, session_id=session_id, task_id=f"zues:session#foo:task#2_{salt}",
user_input=user_input_2)
await super_agent.async_run(user_id=user_id, session_id=session_id, task_id=f"zues:session#foo:task#3_{salt}",
user_input=user_input_3)
await super_agent.async_run(user_id=user_id, session_id=session_id, task_id=f"zues:session#foo:task#4_{salt}",
user_input=user_input_4)
# Final task: Add AWorld comparison
await super_agent.async_run(user_id=user_id, session_id=session_id, task_id=f"zues:session#foo:task#5_{salt}",
user_input="""Please extend the comparative analysis section to include AWorld's Memory Module [https://github.com/inclusionAI/AWorld/].
Focus on:
- Integration with the overall AWorld architecture
- Unique features and capabilities
- Performance characteristics
- Implementation differences
- Potential advantages and limitations
- Comparative analysis with all previously analyzed systems
""")
logger.info(f"✅ Session {session_id} completed")
# if __name__ == '__main__':
# load_dotenv()
#
# init_postgres_memory()
# # Run the multi-session example with concrete learning tasks
# asyncio.run(_run_single_session_examples())
@@ -0,0 +1,137 @@
SELF_EVOLVING_AGENT_PROMPT = """
<system_instruction>
You are an advanced AI assistant powered by a large language model, operating within the AWorld framework. Your purpose is to assist users with a wide range of tasks by leveraging your knowledge and capabilities.
## Core Capabilities
You are designed to:
1. **Understand and respond** to user queries with accurate, helpful information
2. **Reason** through complex problems step by step
3. **Generate** creative content based on user requirements
4. **Execute** tasks using available tools when appropriate
5. **Learn** from interactions to better serve users over time
## Task Approach
When addressing user requests:
1. **Analyze the request** carefully to understand the user's intent and needs
2. **Plan your approach** by breaking down complex tasks into manageable steps
3. **Use available tools** when necessary to gather information or perform actions
4. **Provide clear explanations** of your reasoning and actions
5. **Verify your responses** for accuracy, relevance, and completeness before delivering them
## Communication Guidelines
1. **Be concise** but thorough in your responses
2. **Use appropriate formatting** to enhance readability (headings, bullet points, code blocks)
3. **Adapt your tone** to match the context and user's communication style
4. **Acknowledge limitations** when you're uncertain or when a request is beyond your capabilities
5. **Seek clarification** when user requests are ambiguous or incomplete
## Tool Usage
When using tools:
1. **Select the appropriate tool** based on the task requirements
2. **Explain your reasoning** for using a particular tool
3. **Use tools efficiently** to minimize unnecessary operations
4. **Interpret tool outputs** accurately and incorporate them into your response
5. **Handle errors gracefully** if tools fail or return unexpected results
6. save file use tool[filesystem]
<agent_experiences>
{{agent_experiences}}
</agent_experiences>
<history>
{{history}}
</history>
<cur_time>
{{cur_time}}
</cur_time>
</system_instruction>
"""
RESEARCH_PROMPT = """
You are a research-oriented AI agent, specializing in conducting thorough investigations and generating comprehensive research reports for the user.
You excel at searching, collecting, analyzing, and synthesizing information from various sources such as the web, academic papers, and documentation.
Your workflow:
1. Carefully analyze the user's research topic or question.
2. Break down the research into clear, manageable sub-tasks.
3. Use the available tools (browser, search, file processing, etc.) to gather relevant and credible information for each sub-task.
4. After each tool usage, clearly explain the findings, your reasoning, and propose the next step.
5. Critically evaluate and cross-verify information from multiple sources to ensure accuracy and depth.
6. Organize and summarize the collected information logically, highlighting key insights, comparisons, and conclusions.
7. When you believe the research is complete, output the final answer in <answer></answer> tags, and your reasoning process in <think></think> tags.
Tool Usage Guidelines:
1. Search Tools: Use google-search/tavily-mcp to find relevant information about research topics
2. Browser Tools: Use ms-playwright/tavily-mcp to access specific websites and extract detailed information
3. File Tools: Use filesystem to save research findings and final reports
4. Github Tools: Use github-mcp-server to find repository
IMPORTANT - File Writing Instructions:
When you need to write content to a local file, you MUST use the filesystem#write_file tool with the following EXACT format:
CORRECT USAGE EXAMPLE:
{
"file_path": "ai_memory_systems_research.md",
"content": "# AI Memory System report ....",
"session_id": "session_id20250716143736"
}
REQUIRED PARAMETERS:
- file_path: Complete file path (e.g., "output/report.md", "data/findings.md")
- content: Complete content to be written (must be a string)
- session_id: Current session identifier
ERROR PREVENTION:
- NEVER call filesystem#write_file with only session_id
- ALWAYS provide both file_path and content
- Ensure content is a complete string, not empty
- Use proper file extensions (.md for markdown, .txt for text, etc.)
Best Practices:
- Create organized file structures (e.g., "output/reports/", "data/research/")
- Use descriptive file names
- Include comprehensive content in a single write operation
- Verify information before writing to files
Error Handling:
- If a tool call fails, try alternative approaches
- If filesystem#write_file fails, check that all required parameters are provided
- If search results are insufficient, try different search terms or tools
Final Report Requirements:
- Save the complete research report as a markdown file
- Include all sections: system introduction, core principles, architecture, applications, pros/cons, comparisons, future trends
- Use proper markdown formatting with headers, lists, and code blocks
- Ensure the report is comprehensive and well-structured
Available Context:
<agent_experiences>
{{agent_experiences}}
</agent_experiences>
<history>
{{history}}
</history>
<cur_time>
{{cur_time}}
</cur_time>
Now, here is the research task. Please proceed step by step, using the appropriate tools, and provide a high-quality research report!
"""
SELF_EVOLVING_USER_INPUT_REWRITE_PROMPT = """
<user_profiles>
{user_profiles}
</user_profiles>
<similar_messages_history>
{similar_messages_history}
</similar_messages_history>
<knowledge_base>
</knowledge_base>
{user_input}
"""
@@ -0,0 +1,37 @@
import asyncio
import logging
from dotenv import load_dotenv
from aworld.memory.main import MemoryFactory
from aworld.memory.models import MessageMetadata
from tests.memory.short_term.utils import add_mock_messages
async def run():
load_dotenv()
MemoryFactory.init()
memory = MemoryFactory.instance()
metadata = MessageMetadata(
user_id="zues",
session_id="session#foo",
task_id="zues:session#foo:task#1",
agent_id="super_agent",
agent_name="super_agent"
)
await add_mock_messages(memory, metadata)
# Get and print all messages
items = memory.get_all(filters={
"user_id": metadata.user_id,
"agent_id": metadata.user_id,
"session_id": metadata.session_id,
"task_id": metadata.session_id
})
for item in items:
logging.info(f"{type(item)}: {item.content}")
# if __name__ == '__main__':
# asyncio.run(run())
@@ -0,0 +1,59 @@
import asyncio
import logging
import os
from dotenv import load_dotenv
from aworld.core.memory import AgentMemoryConfig
from aworld.memory.main import MemoryFactory
from aworld.memory.models import MessageMetadata, MemoryHumanMessage
from tests.memory.short_term.utils import add_mock_messages
from tests.memory.utils import init_postgres_memory
async def run():
load_dotenv()
# init_postgres_memory()
memory = MemoryFactory.instance()
metadata = MessageMetadata(
user_id="user_id",
session_id="session_id",
task_id="task_id",
agent_id="self_evolving_agent",
agent_name="self_evolving_agent"
)
# Get and print all messages
items = memory.get_all(filters={
"user_id": metadata.user_id,
"agent_id": metadata.agent_id,
"session_id": metadata.session_id,
"task_id": metadata.task_id
})
summary_config = AgentMemoryConfig(
enable_summary=False,
summary_rounds=2,
summary_model="xxx"
)
await add_mock_messages(memory, metadata, memory_config=summary_config)
await memory.add(MemoryHumanMessage(content="new1",metadata= metadata))
await memory.add(MemoryHumanMessage(content="new2",metadata=metadata))
await memory.add(MemoryHumanMessage(content="new3",metadata=metadata))
retrival_memory = memory.get_last_n(last_rounds=6, filters={
"user_id": metadata.user_id,
"agent_id": metadata.agent_id,
"session_id": metadata.session_id,
"task_id": metadata.task_id
})
logging.info("================== RETRIVAL ==================")
for item in retrival_memory:
logging.info(f"{item.memory_type}: {item.content}")
if __name__ == '__main__':
asyncio.run(run())
@@ -0,0 +1,75 @@
import asyncio
import logging
from dotenv import load_dotenv
from aworld.core.memory import MemoryConfig, VectorDBConfig, EmbeddingsConfig
from aworld.memory.main import MemoryFactory
from aworld.memory.models import MessageMetadata
from tests.memory.short_term.utils import add_mock_messages
async def init():
load_dotenv()
MemoryFactory.init(config=MemoryConfig(
provider="aworld",
embedding_config=EmbeddingsConfig(
provider="ollama",
base_url="http://localhost:11434",
model_name="nomic-embed-text"
),
vector_store_config=VectorDBConfig(
provider="chroma",
config=
{
"chroma_data_path": "./chroma_db",
"collection_name": "aworld",
}
)
))
async def run():
await init()
memory = MemoryFactory.instance()
metadata = MessageMetadata(
user_id="zues",
session_id="session#foo",
task_id="zues:session#foo:task#1",
agent_id="super_agent",
agent_name="super_agent"
)
await add_mock_messages(memory, metadata)
# Get and print all messages
items = memory.get_all(filters={
"user_id": metadata.user_id,
"agent_id": metadata.user_id,
"session_id": metadata.session_id,
"task_id": metadata.session_id
})
for item in items:
logging.info(f"{type(item)}: {item.content}")
async def run_search():
memory = MemoryFactory.instance()
metadata = MessageMetadata(
user_id="zues",
session_id="session#foo",
task_id="zues:session#foo:task#1",
agent_id="super_agent",
agent_name="super_agent"
)
results = memory.search("recommend some outdoor sports", limit=10, filters={
"user_id": metadata.user_id,
"agent_id": metadata.user_id,
"session_id": metadata.session_id,
"task_id": metadata.session_id
})
for result in results:
logging.info(f"search result {type(result)}: {result.id}[{result.metadata['score']}]{result.content}")
# if __name__ == '__main__':
# asyncio.run(run())
# asyncio.run(run_search())
@@ -0,0 +1,42 @@
import asyncio
import logging
import os
from dotenv import load_dotenv
from aworld.memory.db.postgres import PostgresMemoryStore
from aworld.memory.main import MemoryFactory
from aworld.memory.models import MessageMetadata
from tests.memory.short_term.utils import add_mock_messages
async def run():
load_dotenv()
postgres_memory_store = PostgresMemoryStore(db_url=os.getenv("MEMORY_STORE_POSTGRES_DSN"))
MemoryFactory.init(custom_memory_store=postgres_memory_store)
memory = MemoryFactory.instance()
metadata = MessageMetadata(
user_id="zues",
session_id="session#foo",
task_id="zues:session#foo:task#1",
agent_id="super_agent",
agent_name="super_agent"
)
memory.delete_items(message_types=['init','message'], session_id=metadata.session_id, task_id=metadata.task_id)
await add_mock_messages(memory, metadata)
# Get and print all messages
items = memory.get_all(filters={
"user_id": metadata.user_id,
"agent_id": metadata.user_id,
"session_id": metadata.session_id,
"task_id": metadata.session_id
})
for item in items:
logging.info(f"{type(item)}: {item.content}, {item.created_at}")
#
# if __name__ == '__main__':
# asyncio.run(run())
@@ -0,0 +1,110 @@
import json
import logging
from aworld.core.memory import MemoryBase, AgentMemoryConfig
from aworld.memory.models import MemoryAIMessage, MemoryToolMessage, MessageMetadata, MemorySystemMessage, \
MemoryHumanMessage
from aworld.models.model_response import Function, ToolCall
async def add_mock_messages(memory: MemoryBase, metadata: MessageMetadata, memory_config: AgentMemoryConfig = AgentMemoryConfig()):
# Add system message 🤖
system_content = """
<system_instruction>
You are an advanced AI assistant powered by a large language model, operating within the AWorld framework. Your purpose is to assist users with a wide range of tasks by leveraging your knowledge and capabilities.
## Core Capabilities
You are designed to:
1. **Understand and respond** to user queries with accurate, helpful information
2. **Reason** through complex problems step by step
3. **Generate** creative content based on user requirements
4. **Execute** tasks using available tools when appropriate
5. **Learn** from interactions to better serve users over time
## Task Approach
When addressing user requests:
1. **Analyze the request** carefully to understand the user's intent and needs
2. **Plan your approach** by breaking down complex tasks into manageable steps
3. **Use available tools** when necessary to gather information or perform actions
4. **Provide clear explanations** of your reasoning and actions
5. **Verify your responses** for accuracy, relevance, and completeness before delivering them
## Communication Guidelines
1. **Be concise** but thorough in your responses
2. **Use appropriate formatting** to enhance readability (headings, bullet points, code blocks)
3. **Adapt your tone** to match the context and user's communication style
4. **Acknowledge limitations** when you're uncertain or when a request is beyond your capabilities
5. **Seek clarification** when user requests are ambiguous or incomplete
## Tool Usage
When using tools:
1. **Select the appropriate tool** based on the task requirements
2. **Explain your reasoning** for using a particular tool
3. **Use tools efficiently** to minimize unnecessary operations
4. **Interpret tool outputs** accurately and incorporate them into your response
5. **Handle errors gracefully** if tools fail or return unexpected results
6. save file use tool[filesystem]
<agent_experiences>
[]
</agent_experiences>
<history>
</history>
<cur_time>
2025-07-07 17:06:25
</cur_time>
</system_instruction>
"""
await memory.add(MemorySystemMessage(content=system_content, metadata=metadata), agent_memory_config=memory_config)
# Add user message 👤
user_content = """
<user_profiles>
[]
</user_profiles>
<similar_messages_history>
[]
</similar_messages_history>
<knowledge_base>
</knowledge_base>
I like play outdoor sports(basketball, tennis, golf, etc.), please recommend some outdoor sports, save it use markdown
"""
await memory.add(MemoryHumanMessage(content=user_content, metadata=metadata), agent_memory_config=memory_config)
# Add assistant message 🤖
assistant_content = "I'll recommend some popular outdoor sports and save them in a markdown file for you. Here are some great outdoor sports activities:"
# Create ToolCall object
function = Function(
name="mcp__filesystem__write_file",
arguments=json.dumps({
"path": "outdoor_sports_recommendations.md",
"content": "# Outdoor Sports Recommendations\n\nHere are some excellent outdoor sports to try:\n\n## Team Sports\n- Soccer\n- Ultimate Frisbee\n- Beach Volleyball\n- Rugby\n\n## Water Sports\n- Kayaking\n- Stand-up Paddleboarding (SUP)\n- Surfing\n- Open Water Swimming\n\n## Adventure Sports\n- Rock Climbing\n- Mountain Biking\n- Trail Running\n- Orienteering\n\n## Winter Sports\n- Skiing (Alpine/Cross-country)\n- Snowboarding\n- Ice Climbing\n- Snowshoeing\n\n## Individual Sports\n- Golf\n- Tennis\n- Archery\n- Disc Golf\n\n## Extreme Sports\n- Paragliding\n- Bungee Jumping\n- Whitewater Rafting\n- Skydiving\n\nRemember to always use proper safety equipment and get proper training before trying new sports!"
})
)
tool_call = ToolCall(
id="fc-249231de-7efb-4741-b659-2ab8696065cc",
type="function",
function=function
)
await memory.add(MemoryAIMessage(content=assistant_content, tool_calls=[tool_call], metadata=metadata), agent_memory_config=memory_config)
# Add tool response message 🛠️
tool_content = "Successfully wrote to outdoor_sports_recommendations.md"
await memory.add(MemoryToolMessage(
content=tool_content,
tool_call_id="fc-249231de-7efb-4741-b659-2ab8696065cc",
status="success",
metadata=metadata
), agent_memory_config=memory_config)
logging.info("mock messages added")
@@ -0,0 +1,22 @@
import asyncio
from dotenv import load_dotenv
from tests.memory.agent.self_evolving_agent import SuperAgent
async def _run_single_task_examples() -> None:
"""
Run examples with a single task.
Demonstrates basic agent interaction with outdoor sports topic.
"""
super_agent = SuperAgent(id="super_agent", name="super_agent")
user_id = "zues"
session_id = "session#foo"
await super_agent.async_run(user_id=user_id, session_id=session_id,
task_id="zues:session#foo:task#1",
user_input="please recommend some outdoor sports, save it use markdown")
# if __name__ == '__main__':
# load_dotenv()
# asyncio.run(_run_single_task_examples())
@@ -0,0 +1,67 @@
import os
from dotenv import load_dotenv
from aworld.core.memory import MemoryConfig, EmbeddingsConfig, VectorDBConfig, \
MemoryLLMConfig
from aworld.memory.db.postgres import PostgresMemoryStore
from aworld.memory.main import MemoryFactory
def init_memory():
load_dotenv()
MemoryFactory.init(
config=MemoryConfig(
provider="aworld",
llm_config=MemoryLLMConfig(
provider="openai",
model_name=os.environ["LLM_MODEL_NAME"],
api_key=os.environ["LLM_API_KEY"],
base_url=os.environ["LLM_BASE_URL"]
),
embedding_config=EmbeddingsConfig(
provider="ollama",
base_url="http://localhost:11434",
model_name="nomic-embed-text"
),
vector_store_config=VectorDBConfig(
provider="chroma",
config=
{
"chroma_data_path": "./chroma_db",
"collection_name": "aworld",
}
)
))
def init_postgres_memory():
load_dotenv()
postgres_memory_store = PostgresMemoryStore(db_url=os.getenv("MEMORY_STORE_POSTGRES_DSN"))
MemoryFactory.init(
custom_memory_store=postgres_memory_store,
config=MemoryConfig(
provider="aworld",
llm_config=MemoryLLMConfig(
provider="openai",
model_name=os.environ["LLM_MODEL_NAME"],
api_key=os.environ["LLM_API_KEY"],
base_url=os.environ["LLM_BASE_URL"]
),
embedding_config=EmbeddingsConfig(
provider="ollama",
base_url="http://localhost:11434",
model_name="nomic-embed-text"
),
vector_store_config=VectorDBConfig(
provider="chroma",
config=
{
"chroma_data_path": "./chroma_db",
"collection_name": "aworld",
}
)
))