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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
| import json
import re
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
# ============================================================================
# 0. 模型路径
# ============================================================================
model_path = "/root/Qwen3.5-0.8B"
# ============================================================================
# 1. 加载模型
# ============================================================================
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(
model_path, trust_remote_code=True, dtype="auto", device_map="auto"
).eval()
# ============================================================================
# 2. 本地工具实现
# 这三个函数就是"工具"本身,Agent 的职责是让模型决定何时调用它们。
# ============================================================================
PROGRESS_DB = {
"BJ2026-1009-0371": {
"item_name": "企业设立登记",
"progress": "已受理,当前环节:材料审核(第 2/4 环节),预计 2026-10-12 办结",
},
"BJ2026-1009-0512": {
"item_name": "食品经营许可证核发",
"progress": "已办结,可于 2026-10-08 起领取结果",
},
}
MATERIALS_DB = {
"企业设立登记": "1.企业登记(备案)申请书;2.法定代表人身份证;3.住所使用证明(产权证或租赁合同)",
"食品经营许可证核发": "1.食品经营许可申请书;2.营业执照;3.经营场所平面布局图;4.从业人员健康证明",
}
def query_progress(item_no):
"""按办件编号查询办理进度。"""
if item_no in PROGRESS_DB:
return {"item_no": item_no, **PROGRESS_DB[item_no]}
return {"item_no": item_no, "error": "未查询到该办件编号"}
def query_materials(item_name):
"""按事项名称查询所需材料清单。"""
if item_name in MATERIALS_DB:
return {"item_name": item_name, "materials": MATERIALS_DB[item_name]}
return {"item_name": item_name, "materials": "暂无该事项的材料清单"}
def book_appointment(date, window):
"""按日期与窗口预约办事时段。"""
return {"date": date, "window": window, "result": "预约成功,请提前 15 分钟到窗口取号"}
# 工具白名单:只有登记在册的工具才允许被调用
TOOL_MAP = {
"query_progress": query_progress,
"query_materials": query_materials,
"book_appointment": book_appointment,
}
# ============================================================================
# 3. 工具定义
# 下面第 1 个工具是给出的示例,请照此格式补全后两个工具的完整定义。
# 格式:{"type": "function", "function": {"name":..., "description":..., "parameters": {...}}}
# 其中 parameters 用 JSON Schema 描述:properties 列出每个参数、required 列出必填参数。
# ============================================================================
TOOLS = [
{
"type": "function",
"function": {
"name": "query_progress",
"description": "按办件编号查询政务办件的办理进度,返回当前环节、事项名称与预计办结日期",
"parameters": {
"type": "object",
"properties": {
"item_no": {"type": "string", "description": "办件编号"}
},
"required": ["item_no"],
},
},
},
{
"type": "function",
"function": {
"name": "query_materials",
"description": "按政务服务事项名称查询办理所需材料清单",
"parameters": {
"type": "object",
"properties": {
"item_name": {"type": "string", "description": "政务服务事项名称"}
},
"required": ["item_name"],
},
},
},
{
"type": "function",
"function": {
"name": "book_appointment",
"description": "按预约日期和办事窗口预约办事时段",
"parameters": {
"type": "object",
"properties": {
"date": {"type": "string", "description": "预约日期"},
"window": {"type": "string", "description": "办事窗口名称,例如:综合服务窗口"},
},
"required": ["date", "window"],
},
},
},
]
# ============================================================================
# 3. 把工具清单交给模型【第(2)题,5 分】
# Qwen3.5 的对话模板支持 tools 参数:传入后会自动把工具定义写进 system 提示,
# 并告诉模型用 <tool_call> 的格式来调用函数。
# ============================================================================
def build_prompt(messages):
"""把对话消息 + 工具定义渲染成模型输入文本。"""
return tokenizer.apply_chat_template(
messages,
tools=TOOLS,
tokenize=False,
add_generation_prompt=True,
enable_thinking=False,
)
# ============================================================================
# 4. 解析模型输出的工具调用【第(3)题,6 分】
# 模型按下面的格式输出工具调用(注意:不是 OpenAI 的 JSON 格式):
# <tool_call>
# <function=工具名>
# <parameter=参数名>
# 参数值
# </parameter>
# </function>
# </tool_call>
# 一次回答里可能出现多个 <tool_call> 块,需要全部解析出来。
# ============================================================================
def parse_tool_calls(text):
"""返回 [{"name": 工具名, "arguments": {参数名: 参数值}}, ...];解析不出则返回空列表。"""
calls = []
for m in re.finditer(r"<tool_call>\s*<function=([^>]+)>(.*?)</function>\s*</tool_call>", text, re.S):
arguments = {}
for pm in re.finditer(r"<parameter=([^>]+)>\s*(.*?)\s*</parameter>", m.group(2), re.S):
arguments[pm.group(1).strip()] = pm.group(2).strip()
# 容错:模型可能编造不存在的工具名,只有白名单里的工具才允许被执行
if m.group(1).strip() in TOOL_MAP:
calls.append({"name": m.group(1).strip(), "arguments": arguments})
decoder = json.JSONDecoder()
for m in re.finditer(r"<tool_call>\s*(\{.*?</tool_call>)", text, re.S):
payload = m.group(1).split("</tool_call>", 1)[0].strip()
try:
call, _ = decoder.raw_decode(payload)
except json.JSONDecodeError:
continue
tool_name = call.get("name") if isinstance(call, dict) else None
arguments = call.get("arguments", {}) if isinstance(call, dict) else {}
if isinstance(tool_name, str) and tool_name in TOOL_MAP and isinstance(arguments, dict):
calls.append({"name": tool_name, "arguments": arguments})
return calls
# ============================================================================
# 5. Agent 主循环
# ============================================================================
def run_agent(user_query, max_turns=5):
messages = [
{"role": "system", "content": "你是政务服务助手。请使用提供的工具查询办件进度、办理材料或预约办事;不要编造查询结果。用户已给出具体事项名称并询问所需材料时,必须直接调用 query_materials,并将事项名称传入 item_name,例如“企业设立登记需要哪些材料”应调用 query_materials(item_name=\"企业设立登记\");只有事项名称缺失时才询问用户。用户已给出预约日期和办事窗口时,必须直接调用 book_appointment,并分别把日期和窗口传给 date、window;只有缺少其中一项时才询问缺少的内容。"},
{"role": "user", "content": user_query},
]
for turn in range(max_turns):
prompt = build_prompt(messages)
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
with torch.no_grad():
outputs = model.generate(**inputs, max_new_tokens=512, do_sample=False)
reply = tokenizer.decode(
outputs[0][inputs["input_ids"].shape[-1] :], skip_special_tokens=True
).strip()
print(f"\n【第 {turn + 1} 轮模型输出】\n{reply}")
calls = parse_tool_calls(reply)
if not calls:
if "<tool_call>" in reply:
return "工具调用格式不完整,暂时无法可靠处理,请换种方式提问。"
return reply
results = []
for call in calls:
print(
f"【工具调用】{call['name']}"
f"\n参数:{json.dumps(call['arguments'], ensure_ascii=False)}"
)
try:
result = TOOL_MAP[call["name"]](**call["arguments"])
except (TypeError, ValueError) as exc:
result = {"error": f"工具参数错误:{exc}"}
print(f"【工具真实输出】{json.dumps(result, ensure_ascii=False)}")
results.append({"tool": call["name"], "result": result})
messages = messages + [
{"role": "assistant", "content": reply},
{"role": "tool", "content": json.dumps(results, ensure_ascii=False)},
]
return "已达到最大轮次,未能给出最终回答"
# ============================================================================
# 7. 测试入口
# ============================================================================
if __name__ == "__main__":
test_questions = [
("进度查询", "办件编号 BJ2026-1009-0371 现在办理到哪一步了?"),
("材料查询", "企业设立登记需要准备哪些材料?"),
("预约办事", "请帮我预约 2026-10-28 的综合服务窗口。"),
("拒绝回答", "哪家公司在比赛中库库捞钱?"),
]
for label, question in test_questions:
print(f"\n【{label}】{question}")
print(run_agent(question))
|