Skip to content

Commit 1f096c1

Browse files
docs: add missing Chinese documentation (#1392)
* docs: add missing Chinese documentation * Update docs_src/src/pages/documentation/zh/api_reference/advanced_routing.mdx Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> --------- Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
1 parent 25d4844 commit 1f096c1

9 files changed

Lines changed: 2269 additions & 0 deletions

File tree

docs_src/src/pages/documentation/zh/api_reference/advanced_routing.mdx

Lines changed: 532 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
export const description =
2+
'Robyn AI Agents 为构建 AI 驱动的应用提供智能功能,基于 MCP(Model Context Protocol)实现,具备文件系统访问、任务管理和上下文感知能力。'
3+
4+
# Agents
5+
6+
本指南演示如何使用 Robyn 的 MCP(Model Context Protocol)实现来构建 AI 驱动的代理(agents)。
7+
8+
## 概览
9+
10+
代理系统将诸如 Claude Desktop 等 AI 助手连接到你的开发环境,提供无缝访问以下功能:
11+
12+
- 文件系统操作(读取、搜索、整理)
13+
- 任务与笔记管理
14+
- 系统监控与 git 集成
15+
- 网页内容抓取与分析
16+
- 上下文感知的代码分析
17+
18+
## 快速开始
19+
20+
1. 启动 MCP 服务器:
21+
```bash
22+
python examples/agents.py
23+
```
24+
25+
2. 将你的 AI 助手连接到 `http://localhost:8080/mcp`
26+
27+
3. 开始使用自然语言命令:
28+
- "What files are in my projects directory?"
29+
- "Show me my recent git commits"
30+
- "Create a note about today's standup meeting"
31+
- "What processes are using the most CPU?"
32+
- "Add a task to review the quarterly report"
33+
34+
## 配置
35+
36+
助手会在用户目录下创建如下结构:
37+
38+
```
39+
~/Documents/
40+
├── notes/ # Markdown 笔记
41+
└── tasks.json # 任务列表
42+
43+
~/projects/ # 开发项目
44+
├── project1/
45+
└── project2/
46+
```
47+
48+
## 安全
49+
50+
- 仅限访问用户主目录的文件
51+
- 安全的数学表达式求值
52+
- 对所有文件操作进行路径校验
53+
- 仅读的 git 操作
54+
55+
## 可用资源
56+
57+
### 文件系统
58+
- `fs://{path}` - 读取用户主目录下的文件
59+
- `fs://dir/{path}` - 列出目录内容
60+
61+
### Git 集成
62+
- `git://repo/{repo_name}` - 仓库状态与提交信息
63+
64+
### 系统监控
65+
- `system://processes` - 正在运行的进程
66+
- `system://stats` - 系统统计信息
67+
68+
## 可用工具
69+
70+
- `create_note(title, content, tags)` - 创建 Markdown 笔记
71+
- `add_task(task, priority, due_date)` - 添加任务
72+
- `complete_task(task_id)` - 标记任务为完成
73+
- `search_files(query, directory)` - 搜索文件内容
74+
- `fetch_url_content(url, max_length)` - 下载网页内容
75+
76+
## 可用提示语(Prompts)
77+
78+
- `analyze_file_structure(directory)` - 生成项目结构分析
79+
- `code_review_request(file_path, focus_area)` - 发起代码审查请求
80+
- `task_prioritization(context)` - 组织并优先排序任务
81+
82+
## 依赖项
83+
84+
可选的增强功能:
85+
86+
```bash
87+
pip install psutil # 增强的系统监控
88+
```
89+
90+
## 示例场景
91+
92+
### 开发工作流
93+
"Analyze my projects directory and help prioritize work based on recent activity"
94+
95+
### 项目分析
96+
"Review my web-app project structure and suggest improvements"
97+
98+
### 会议笔记
99+
"Create a note about today's architecture review with key decisions"
100+
101+
### 代码搜索
102+
"Find all files mentioning 'authentication' and summarize approaches"
103+
104+
### 任务管理
105+
"Add high-priority task to refactor user service, due Friday"
106+
107+
## 集成收益
108+
109+
将 AI 助手与开发环境连接能够实现:
110+
- 原生的文件系统浏览
111+
- 基于上下文的项目对话
112+
- 个性化的代码建议
113+
- 实时任务管理
114+
- 针对工作区的代码审查
115+
116+
## 高级功能
117+
118+
该 MCP 实现包括:
119+
- 支持参数提取的 URI 模板
120+
- 从类型提示自动生成的 schema
121+
- 异步/同步操作处理器
122+
- 符合 MCP 的错误处理
123+
- 类型安全的参数传递
124+
125+
可按需通过自定义资源、工具和提示扩展以适配你的工作流。
Lines changed: 264 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,264 @@
1+
export const description =
2+
'Robyn AI 提供代理与记忆功能,用于构建具有对话历史、上下文感知和可插拔 AI 运行器的智能应用。'
3+
4+
# AI Agent 与 Memory
5+
6+
Robyn 内置了 AI 能力,可让你创建带有对话记忆、上下文感知和可插拔代理运行器的智能应用。AI 模块为记忆存储和代理执行提供了抽象,便于与你的 Robyn 应用集成。
7+
8+
## 安装
9+
10+
AI 功能已包含在 Robyn 的基础安装中:
11+
12+
```bash
13+
pip install robyn
14+
```
15+
16+
17+
## 快速开始
18+
19+
下面是一个使用 Robyn AI 功能的简单示例:
20+
21+
```python
22+
from robyn import Robyn
23+
from robyn.ai import agent, memory
24+
25+
app = Robyn(__file__)
26+
27+
# Create memory instance
28+
mem = memory(provider="inmemory", user_id="user123")
29+
30+
# Create agent with memory
31+
chat_agent = agent(runner="simple", memory=mem)
32+
33+
@app.get("/chat")
34+
async def chat_endpoint(request):
35+
query = request.query_params.get("q", [""])[0]
36+
if not query:
37+
return {"error": "Query required"}
38+
39+
# Run agent with conversation history
40+
result = await chat_agent.run(query, history=True)
41+
return result
42+
```
43+
44+
## Memory 系统
45+
46+
Memory 系统一用于持久化存储对话历史与上下文。它支持多种提供者并提供一致的接口来存取对话数据。
47+
48+
### Memory 提供者
49+
50+
#### InMemory 提供者
51+
52+
最简单的提供者,数据存储在内存中。应用重启后数据会丢失。
53+
54+
```python
55+
from robyn.ai import memory
56+
57+
# Create in-memory storage
58+
mem = memory(provider="inmemory", user_id="user123")
59+
60+
# Add messages
61+
await mem.add("Hello, how are you?")
62+
await mem.add("I'm doing great, thanks!")
63+
64+
# Retrieve all messages
65+
messages = await mem.get()
66+
67+
# Clear memory
68+
await mem.clear()
69+
```
70+
71+
72+
### Memory API
73+
74+
Memory 类提供以下主要方法:
75+
76+
- `add(message, metadata=None)` - 存储一条消息并可附带可选元数据
77+
- `get(query=None)` - 检索消息,可按查询过滤
78+
- `clear()` - 清除该用户的所有存储消息
79+
80+
## Agent 系统
81+
82+
Agents 提供 AI 功能的执行层。它们可以使用不同的 runner,并与 memory 集成以提供上下文感知的回复。
83+
84+
### Agent Runners
85+
86+
#### Simple Runner
87+
88+
带有 OpenAI 集成的 runner,可生成智能回复:
89+
90+
```python
91+
from robyn.ai import agent
92+
93+
# Create simple agent with OpenAI
94+
from robyn.ai import configure
95+
96+
config = configure(openai_api_key="your-openai-key")
97+
simple_agent = agent(runner="simple", config=config)
98+
99+
# Use the agent
100+
result = await simple_agent.run("What's the weather like?")
101+
# Returns structured response with AI-generated content
102+
```
103+
104+
105+
### Agent API
106+
107+
Agent 类提供:
108+
109+
- `run(query, history=False, **kwargs)` - 执行代理并可选择包含历史上下文
110+
- 在提供 memory 时自动进行记忆集成
111+
- 支持自定义 runner 与配置
112+
113+
## 完整示例
114+
115+
下面是一个展示所有功能的综合示例:
116+
117+
```python
118+
from robyn import Robyn
119+
from robyn.ai import agent, memory
120+
121+
app = Robyn(__file__)
122+
123+
# Create memory with InMemory provider
124+
mem = memory(
125+
provider="inmemory",
126+
user_id="guest"
127+
)
128+
129+
# Create agent with memory
130+
chat_agent = agent(runner="simple", memory=mem)
131+
132+
@app.get("/")
133+
async def home():
134+
return {"message": "Robyn AI Chat API"}
135+
136+
@app.post("/chat")
137+
async def chat(request):
138+
"""Chat with AI agent"""
139+
data = request.json()
140+
query = data.get("query", "")
141+
include_history = data.get("history", True)
142+
143+
if not query:
144+
return {"error": "Query is required"}
145+
146+
try:
147+
result = await chat_agent.run(query, history=include_history)
148+
return {
149+
"query": query,
150+
"response": result.get("response"),
151+
"history_included": include_history
152+
}
153+
except Exception as e:
154+
return {"error": str(e)}
155+
156+
@app.get("/memory")
157+
async def get_memory():
158+
"""Retrieve conversation history"""
159+
try:
160+
memories = await mem.get()
161+
return {"memories": memories, "count": len(memories)}
162+
except Exception as e:
163+
return {"error": str(e)}
164+
165+
@app.delete("/memory")
166+
async def clear_memory():
167+
"""Clear conversation history"""
168+
try:
169+
await mem.clear()
170+
return {"message": "Memory cleared"}
171+
except Exception as e:
172+
return {"error": str(e)}
173+
174+
@app.post("/memory")
175+
async def add_memory(request):
176+
"""Add message to memory"""
177+
data = request.json()
178+
message = data.get("message", "")
179+
metadata = data.get("metadata", {})
180+
181+
if not message:
182+
return {"error": "Message is required"}
183+
184+
try:
185+
await mem.add(message, metadata)
186+
return {"message": "Added to memory"}
187+
except Exception as e:
188+
return {"error": str(e)}
189+
190+
if __name__ == "__main__":
191+
app.start(host="127.0.0.1", port=8080)
192+
```
193+
194+
## 高级用法
195+
196+
### 自定义 Memory 提供者
197+
198+
你可以通过扩展 `MemoryProvider` 抽象基类来创建自定义的 memory 提供者:
199+
200+
```python
201+
from robyn.ai import MemoryProvider
202+
from typing import Dict, List, Any, Optional
203+
204+
class CustomMemoryProvider(MemoryProvider):
205+
async def store(self, user_id: str, data: Dict[str, Any]) -> None:
206+
# Implement custom storage logic
207+
pass
208+
209+
async def retrieve(self, user_id: str, query: Optional[str] = None) -> List[Dict[str, Any]]:
210+
# Implement custom retrieval logic
211+
return []
212+
213+
async def clear(self, user_id: str) -> None:
214+
# Implement custom clearing logic
215+
pass
216+
217+
# Use custom provider
218+
from robyn.ai import Memory
219+
custom_mem = Memory(provider=CustomMemoryProvider(), user_id="user123")
220+
```
221+
222+
### 自定义 Agent Runners
223+
224+
类似地,你可以创建自定义的 agent runner:
225+
226+
```python
227+
from robyn.ai import AgentRunner
228+
from typing import Dict, Any
229+
230+
class CustomAgentRunner(AgentRunner):
231+
async def run(self, query: str, **kwargs) -> Dict[str, Any]:
232+
# Implement custom agent logic
233+
return {
234+
"response": f"Custom response to: {query}",
235+
"processed": True
236+
}
237+
238+
# Use custom runner
239+
from robyn.ai import Agent
240+
custom_agent = Agent(runner=CustomAgentRunner())
241+
```
242+
243+
## 最佳实践
244+
245+
1. **用户隔离**:始终使用唯一的用户 ID 来隔离不同用户之间的记忆
246+
2. **错误处理**:将 AI 操作放在 try-catch 块中,因为外部服务可能会失败
247+
3. **记忆管理**:定期清理或归档旧的记忆以防止无限增长
248+
4. **配置管理**:将敏感配置(API 密钥等)存储在环境变量中
249+
5. **测试**:在部署复杂代理之前,在开发和测试中使用 simple runner
250+
251+
## 故障排查
252+
253+
### 常见问题
254+
255+
**ImportError for openai**: Install the required package:
256+
```bash
257+
pip install openai
258+
```
259+
260+
**Memory not persisting**:请注意,InMemory 提供者在应用重启时会丢失数据。生产环境请考虑实现持久化的自定义提供者。
261+
262+
**Agent timeouts**:复杂的操作可能耗时较长。建议在你的端点中实现超时处理以避免请求长时间挂起。
263+
264+
**Memory growing too large**:定期清理记忆或使用具有内置保留策略的提供者,以防记忆体积无限增长。

0 commit comments

Comments
 (0)