1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
| from typing import List, Dict
import json
class AutoGPTAgent:
"""AutoGPT风格的Agent"""
def __init__(
self,
name: str,
role: str,
goals: List[str],
llm,
tools: Dict[str, callable]
):
self.name = name
self.role = role
self.goals = goals
self.llm = llm
self.tools = tools
self.memory = []
self.task_list = []
def think(self) -> Dict:
"""思考下一步行动"""
prompt = f"""
Name: {self.name}
Role: {self.role}
Goals: {', '.join(self.goals)}
Memory:
{self.format_memory()}
Current Tasks:
{self.format_tasks()}
请决定下一步行动。返回JSON格式:
{{
"thought": "思考过程",
"reasoning": "推理过程",
"plan": "计划",
"criticism": "自我批评",
"action": "行动名称",
"action_input": "行动输入"
}}
"""
response = self.llm.generate(prompt)
try:
return json.loads(response)
except:
return {
"thought": "解析错误",
"action": "finish",
"action_input": ""
}
def execute(self, action: str, action_input: str) -> str:
"""执行行动"""
if action == "finish":
return "任务完成"
if action in self.tools:
result = self.tools[action](action_input)
# 记录到记忆
self.memory.append({
"action": action,
"input": action_input,
"result": result
})
return result
else:
return f"未知行动: {action}"
def format_memory(self) -> str:
"""格式化记忆"""
if not self.memory:
return "No memories yet."
return "\n".join([
f"- {m['action']}: {m['input']} -> {m['result'][:100]}"
for m in self.memory[-5:]
])
def format_tasks(self) -> str:
"""格式化任务列表"""
if not self.task_list:
return "No tasks."
return "\n".join([
f"{i+1}. {task}"
for i, task in enumerate(self.task_list)
])
def run(self, max_iterations: int = 10) -> str:
"""运行Agent"""
for i in range(max_iterations):
# 思考
thought_process = self.think()
print(f"\n=== Iteration {i+1} ===")
print(f"Thought: {thought_process['thought']}")
print(f"Reasoning: {thought_process['reasoning']}")
print(f"Plan: {thought_process['plan']}")
print(f"Criticism: {thought_process['criticism']}")
# 执行
action = thought_process['action']
action_input = thought_process['action_input']
result = self.execute(action, action_input)
print(f"Action: {action}")
print(f"Result: {result[:200]}")
# 检查是否完成
if action == "finish":
return result
return "达到最大迭代次数"
# 使用示例
def search_web(query: str) -> str:
"""搜索网络"""
return f"搜索'{query}'的结果..."
def write_file(content: str) -> str:
"""写入文件"""
return "文件已写入"
def read_file(filename: str) -> str:
"""读取文件"""
return f"文件{filename}的内容..."
tools = {
"search": search_web,
"write": write_file,
"read": read_file
}
agent = AutoGPTAgent(
name="Researcher",
role="AI研究员",
goals=["研究最新AI技术", "生成研究报告"],
llm=OpenAI(temperature=0),
tools=tools
)
result = agent.run()
print(result)
|