介绍
examples 下都是对框架封装的类的调用,基本流程是构造参数,调用框架方法,检查结果。意义是使用框架开发的一些示范代码。
demo 1-基础工具调用
介绍
工具是类,返回体也是类。
展示了注册了的工具怎么调用,把调用和过程量的打印封装成一个函数。本质上就是调用了工具类内的 execute() 函数。
示例展示功能如下:
-
写入文件
-
读取文件
-
编辑文件
-
使用命令
源码:
工具都在 /tools/ 下,前三个都在 file_tools.py ,最后一个在 bash_tool.py。
示例代码
file 和 bash各讲解一个,file 的原理基本差不多。
demo_write_tool
这个工具就两个入参:路径,内容。调用完输出一下文件看看是否正常。
文件都用 tempfile 包创建临时文件,操作完自动释放。
import asyncio
import tempfile
from pathlib import Path
from mini_agent.tools import BashTool, EditTool, ReadTool, WriteTool
async def demo_write_tool():
"""Demo: Write a new file."""
print("\n" + "=" * 60)
print("Demo 1: WriteTool - Create a new file")
print("=" * 60)
with tempfile.TemporaryDirectory() as tmpdir:
#这句函数是创建了一个临时的目录,所以不能用赋值代替
file_path = Path(tmpdir) / "hello.txt"
tool = WriteTool()
result = await tool.execute(
path=str(file_path), content="Hello, Mini Agent!\nThis is a test file."
)
if result.success:
print(f"✅ File created: {file_path}")
print(f"Content:\n{file_path.read_text()}")
else:
print(f"❌ Failed: {result.error}")
demo_bash_tool
bash_tool 以字符串传入命令,返回 result,如果成功就取 result.content
async def demo_bash_tool():
"""Demo: Execute bash commands."""
print("\n" + "=" * 60)
print("Demo 4: BashTool - Execute bash commands")
print("=" * 60)
tool = BashTool()
# Example 1: List files
print("\nCommand: ls -la")
result = await tool.execute(command="ls -la")
if result.success:
print(f"✅ Command executed successfully")
print(f"Output:\n{result.content[:200]}...")
# Example 2: Get current directory
print("\nCommand: pwd")
result = await tool.execute(command="pwd")
if result.success:
print(f"✅ Current directory: {result.content.strip()}")
# Example 3: Echo
print("\nCommand: echo 'Hello from BashTool!'")
result = await tool.execute(command="echo 'Hello from BashTool!'")
if result.success:
print(f"✅ Output: {result.content.strip()}")
demo 2-简单 Agent 执行示例
介绍
这个 demo 用 Agent 机制执行了两个简单任务。
一个是写个 python 有参函数并且执行;
另一个是用 bash 查看时间,文件列表,文件数。
准备工作:
需要先到 config.yaml 里配好 apikey。运行时遇到了相对路径问题,需要把 config 和 system_prompt 路径都先退到上级再拼相对目录。
源码:
用到了/config 下的配置。LLM 和 Agent 类也是用的源码的。
示例代码
主函数
从输出就可以看出,这两个函数分别执行了两个任务。
async def main():
"""Run all demos."""
print("=" * 60)
print("Simple Agent Usage Examples")
print("=" * 60)
print("\nThese examples show how to create an agent and give it tasks.")
print("The agent uses LLM to decide which tools to call.\n")
# Run demos
await demo_file_creation()
print("\n" * 2)
await demo_bash_task()
print("\n" + "=" * 60)
print("All demos completed! ✅")
print("=" * 60)
demo_file_creation
任务内容:
写一个 print 函数,调用一下。
task = """
Create a Python file named 'hello.py' that:
1. Defines a function called greet(name)
2. The function prints "Hello, {name}!"
3. Calls the function with name="Mini Agent"
"""
示例代码内容:
控制台能看到配置加载,llm/agent/task构造,任务执行过程的完整日志。
任务执行过程调用了 agent.run() ,执行实现要看源码。
伪代码解释:
-
加载 apikey
- 检验文件,值是否存在
- 加载
-
加载 system_prompt
- 检验文件,值是否存在
- 加载
-
构造 agent
- 构造 llm_client
- 构造 tools
- 组装 agent(llm_client,tools,system_prompt)
-
agent 执行 task
- 用字符串说明 task
- task 就是 user_prompt.content,加入 agent 任务列表
- agent.run() 直接执行
demo_bash_task
任务内容:
用 bash 查看时间,文件列表,文件数。
task = """
Use bash commands to:
1. Show the current date and time
2. List all Python files in the current directory
3. Count how many Python files exist
"""
控制台输出
就拿到一个任务为例
可以看到整个任务完成过程:
- 思考
- 调用工具
- 思考
- 输出
============================================================
Demo: Agent-Driven File Creation
============================================================
📁 Workspace: /var/folders/d8/ds6m19mn1j919jw4b5m6yj7c0000gn/T/tmpgz3p8vr9
📝 Task:
Create a Python file named 'hello.py' that:
1. Defines a function called greet(name)
2. The function prints "Hello, {name}!"
3. Calls the function with name="Mini Agent"
============================================================
🤖 Agent is working...
📝 Log file: /Users/swufan/.mini-agent/log/agent_run_20260508_002018.log
╭──────────────────────────────────────────────────────────╮
│ 💭 Step 1/10 │
╰──────────────────────────────────────────────────────────╯
🧠 Thinking:
The user wants me to create a Python file named 'hello.py' with specific requirements:
1. Define a function called greet(name)
2. The function prints "Hello, {name}!"
3. Calls the function with name="Mini Agent"
This is straightforward. I'll create the file with the appropriate content.
🔧 Tool Call: write_file
Arguments:
{
"content": "def greet(name):\n print(f\"Hello, {name}!\")\n\ngreet(name=\"Mini Agent\")",
"path": "hello.py"
}
✓ Result: Successfully wrote to /var/folders/d8/ds6m19mn1j919jw4b5m6yj7c0000gn/T/tmpgz3p8vr9/hello.py
⏱️ Step 1 completed in 4.53s (total: 4.53s)
╭──────────────────────────────────────────────────────────╮
│ 💭 Step 2/10 │
╰──────────────────────────────────────────────────────────╯
🧠 Thinking:
The user requested me to create a Python file named 'hello.py' with specific requirements. I've successfully created the file with:
1. A function called greet(name)
2. The function prints "Hello, {name}!" using an f-string
3. Calls the function with name="Mini Agent"
The file has been created successfully.
🤖 Assistant:
I've created `hello.py` with:
- A `greet(name)` function that prints "Hello, {name}!"
- A call to the function with `name="Mini Agent"`
The file is ready at `hello.py`.
⏱️ Step 2 completed in 4.38s (total: 8.90s)
============================================================
✅ Agent completed the task!
============================================================
Agent's response:
I've created `hello.py` with:
- A `greet(name)` function that prints "Hello, {name}!"
- A call to the function with `name="Mini Agent"`
The file is ready at `hello.py`.
============================================================
📄 Created file content:
============================================================
def greet(name):
print(f"Hello, {name}!")
greet(name="Mini Agent")
============================================================
demo 3- Agent 共享 session
介绍
记忆:
agent 持久化记忆一般有两种,这个项目展示 session。
- 短期对话的上下文记忆,可以叫 session
- 以持久化存储的总结/预设,有 summary/readme
示例的两个函数内容:
展示 SessionNoteTool ,RecallNoteTool 的功能。
使用 SessionNoteTool ,RecallNoteTool 演示两个 agent 怎么跨会话共享记忆。轻量级记忆实现也值得学习。
SessionNoteTool:
这个工具是在文件里写入 json ,根据关键词检索。
示例代码
主函数
老规矩先看主函数,就是调用了一下两个方法:
- 直接调用笔记功能
- 演示带有笔记的agent
async def main():
"""Run all demos."""
#...
# Run demos
await demo_direct_note_usage()
print("\n" * 2)
await demo_agent_with_notes()
demo_direct_note_usage
展示记录与读取工具的功能。
调用工具 SessionNoteTool 写入几条记忆到文件,再用 RecallNoteTool 找回记忆展示,再输出文件查看 agent_memory.json 。
# Record some notes
print("\n📝 Recording notes...")
result = await record_tool.execute(
content="User is a Python developer working on agent systems",
category="user_info",
)
print(f" ✓ {result.content}")
result = await record_tool.execute(
content="Project name: mini-agent, Tech: Python 3.12 + async",
category="project_info",
)
print(f" ✓ {result.content}")
result = await record_tool.execute(
content="User prefers concise, well-documented code",
category="user_preference",
)
print(f" ✓ {result.content}")
# Recall all notes
print("\n🔍 Recalling all notes...")
result = await recall_tool.execute()
print(result.content)
# Recall filtered notes
print("\n🔍 Recalling user preferences only...")
result = await recall_tool.execute(category="user_preference")
print(result.content)
# Show the memory file
print("\n📄 Memory file content:")
print("=" * 60)
notes = json.loads(Path(note_file).read_text())
print(json.dumps(notes, indent=2, ensure_ascii=False))
print("=" * 60)
📝 Recording notes...
✓ Recorded note: User is a Python developer working on agent systems (category: user_info)
✓ Recorded note: Project name: mini-agent, Tech: Python 3.12 + async (category: project_info)
✓ Recorded note: User prefers concise, well-documented code (category: user_preference)
🔍 Recalling all notes...
Recorded Notes:
1. [user_info] User is a Python developer working on agent systems
(recorded at 2026-05-08T00:34:20.847956)
2. [project_info] Project name: mini-agent, Tech: Python 3.12 + async
(recorded at 2026-05-08T00:34:20.848073)
3. [user_preference] User prefers concise, well-documented code
(recorded at 2026-05-08T00:34:20.848160)
🔍 Recalling user preferences only...
Recorded Notes:
1. [user_preference] User prefers concise, well-documented code
(recorded at 2026-05-08T00:34:20.848160)
📄 Memory file content:
============================================================
[
{
"timestamp": "2026-05-08T00:34:20.847956",
"category": "user_info",
"content": "User is a Python developer working on agent systems"
},
{
"timestamp": "2026-05-08T00:34:20.848073",
"category": "project_info",
"content": "Project name: mini-agent, Tech: Python 3.12 + async"
},
{
"timestamp": "2026-05-08T00:34:20.848160",
"category": "user_preference",
"content": "User prefers concise, well-documented code"
}
]
============================================================
demo_agent_with_notes
流程比较长,简单梳理一下。
建立了两个 agent
第一个 agent:
task 为介绍了用户信息,用户偏好,要求记录这些信息。
思考
分别执行了 write tool,session tool 记录了 readme.md,agent_memory 。
第二个 agent:
task 为” 我回来了,你还记得我是谁吗?”
思考
执行了 RecallNoteTool 获得了信息。
会发现调用了 RecallnoteTool,也就是只获取了 session,没获取 readme。
demo 4- 完整 Agent
介绍
上来看到两个函数,大致都是初始化智能体,然后执行任务。第一个 Agent 任务是给了一个写 python 文件实现加减的复杂任务。第二个 Agent 任务通过多轮对话交给 Agent。
完整复杂任务
直接一次性提交复杂任务,最后展示文件,函数,记忆
# Task: Complex task that uses multiple tools
task = """
Please help me with the following tasks:
1. Create a Python script called 'calculator.py' that:
- Has functions for add, subtract, multiply, divide
- Has a main() function that demonstrates usage
- Includes proper docstrings and type hints
2. Create a README.md file that:
- Describes the calculator script
- Shows how to run it
- Lists the available functions
3. Test the calculator by running it with bash
4. Remember this project info:
- Project: Simple Calculator
- Language: Python
- Purpose: Demonstration of agent capabilities
"""
print("🤖 Agent is working...\n")
agent.add_user_message(task)
# execute task
try:
result = await agent.run()
#show response
print(f"\nAgent's final response:\n{result}\n")
#show files
#show functions
#show memorys
多轮对话任务
用数组储存多轮任务,循环提交,每次执行后查看结果。
# Conversation turns
conversations = [
"Create a file called 'data.txt' with the numbers 1 to 5, one per line.",
"Now read the file and tell me what's in it.",
"Count how many lines are in the file using bash.",
]
for i, message in enumerate(conversations, 1):
print(f"\n{'=' * 60}")
print(f"Turn {i}:")
print(f"{'=' * 60}")
print(f"User: {message}\n")
agent.add_user_message(message)
try:
result = await agent.run()
print(f"Agent: {result}\n")
对比
两个智能体展示了不同的任务场景。一个是复杂任务,体现了 Agent 的自主规划能力。另一个有点像 ClaudeCode,交互式的 CLI 场景,有人机交互的过程。
两者的记忆也很有意思。前者用的文档持久化会话记忆,好处是可以跨对话共享记忆,可追溯。可以联想到 LangGraph 里的状态,拥有快照,还能支持并发写入,可以回滚。后者用的会话内存记忆,把人的消息,LLM 的消息交替写入记忆,很像 LangChain,ClaudeCode。还是场景不同导致的。
666