Repository navigation
Expand file tree
/
Copy pathreact_demo.py
More file actions
177 lines (141 loc) · 5.78 KB
/
Copy pathreact_demo.py
File metadata and controls
177 lines (141 loc) · 5.78 KB
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
import os
import re
from dotenv import load_dotenv
from openai import OpenAI
load_dotenv()
API_KEY = os.getenv("LLM_API_KEY", "")
OPENAPI_ENDPOINT = os.getenv("LLM_BASE_URL", "")
MODEL = os.getenv("LLM_MODEL_ID", "qwen3.7-plus")
# 这个小型知识库是故意做成本地的,方便初学时稳定复现 ReAct 流程。
KNOWLEDGE_BASE = [
{
"keywords": ["小王子", "作者", "出生"],
"result": "《小王子》的作者是安托万·德·圣埃克苏佩里,他出生于 1900 年。"
},
{
"keywords": ["小王子", "作者"],
"result": "《小王子》的作者是安托万·德·圣埃克苏佩里。"
},
{
"keywords": ["太阳系", "最大", "行星"],
"result": "太阳系最大的行星是木星。"
},
{
"keywords": ["木星", "卫星"],
"result": "木星有很多天然卫星,其中较知名的包括木卫一、木卫二、木卫三和木卫四。"
},
]
def search_tool(query: str) -> str:
query = query.strip()
for item in KNOWLEDGE_BASE:
if all(keyword in query for keyword in item["keywords"]):
return item["result"]
return f"没有在本地知识库中找到“{query}”的结果。"
def calculator_tool(expression: str) -> str:
expression = expression.strip()
# 这里只允许最基础的四则运算字符,避免 demo 中直接执行任意代码。
if not re.fullmatch(r"[\d\.\+\-\*\/\(\)\s]+", expression):
return f"表达式不合法:{expression}"
try:
return str(eval(expression, {"__builtins__": {}}, {}))
except Exception as error:
return f"计算失败:{error}"
class ReActDemo:
def __init__(self) -> None:
if not API_KEY or not OPENAPI_ENDPOINT or not MODEL:
raise ValueError("请先在 .env 中配置 LLM_API_KEY、LLM_BASE_URL、LLM_MODEL_ID。")
self.client = OpenAI(api_key=API_KEY, base_url=OPENAPI_ENDPOINT)
self.model = MODEL
self.tools = {
"Search": {
"description": "查询本地知识库中的事实信息。适合作者、年份、常识类问题。",
"func": search_tool,
},
"Calculator": {
"description": "计算数学表达式。只支持数字、括号和 + - * /。",
"func": calculator_tool,
},
}
def run(self, question: str, max_steps: int = 5) -> str:
history = ""
tool_text = "\n".join(
f"- {name}: {info['description']}" for name, info in self.tools.items()
)
for step in range(1, max_steps + 1):
prompt = f"""你是一个 ReAct 智能体练习助手,请始终使用中文思考和中文回答。
你必须严格遵循下面这个循环:
Thought: 说明你当前的思考
Action: 只能是以下两种格式之一
- Search[查询内容]
- Calculator[数学表达式]
- Finish[最终答案]
规则:
1. 每一轮只能输出一个 Thought 和一个 Action。
2. 遇到事实查询,优先调用 Search。
3. 遇到计算问题,必须调用 Calculator,不要心算。
4. 如果问题同时包含“查信息”和“做计算”,请先查再算。
5. 当你已经拿到足够信息后,再输出 Finish[最终答案]。
6. 不要输出 Observation,Observation 由系统提供给你。
可用工具:
{tool_text}
当前问题:
{question}
历史记录:
{history if history else "无"}
"""
response = self.client.chat.completions.create(
model=self.model,
messages=[
{
"role": "system",
"content": "你是一个严格遵守格式的 ReAct 教学示例助手,必须输出 Thought 和 Action。"
},
{"role": "user", "content": prompt},
],
temperature=0,
)
reply = (response.choices[0].message.content or "").strip()
print(f"\n========== 第 {step} 轮 ==========")
print(reply)
thought_match = re.search(
r"Thought[::]\s*(.*?)(?:\nAction[::]|\Z)", reply, re.S
)
action_match = re.search(
r"Action[::]\s*([A-Za-z_]+)\[(.*)\]\s*$", reply, re.S
)
if not thought_match or not action_match:
return "模型输出未遵循 ReAct 格式,建议重试一次。"
thought = thought_match.group(1).strip()
action_name = action_match.group(1).strip()
action_input = action_match.group(2).strip()
if action_name == "Finish":
return action_input
if action_name not in self.tools:
observation = f"工具不存在:{action_name}"
else:
observation = self.tools[action_name]["func"](action_input)
print(f"Observation: {observation}")
history += (
f"Thought: {thought}\n"
f"Action: {action_name}[{action_input}]\n"
f"Observation: {observation}\n\n"
)
return "达到最大轮数,仍未得到最终答案。"
if __name__ == "__main__":
agent = ReActDemo()
print("ReAct Demo 已启动,输入 exit 退出。")
print("推荐先试这个 case:")
print("《小王子》的作者出生于哪一年?请再计算 2026 - 出生年份。")
while True:
question = input("\n你:").strip()
if not question:
continue
if question.lower() in {"exit", "quit"}:
print("再见。")
break
try:
final_answer = agent.run(question)
print(f"\n最终答案:{final_answer}")
except Exception as error:
print(f"\n运行失败:{error}")
break