single_sandbox.py
10.4 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
178
179
180
181
182
183
184
185
186
187
"""单次补货 · 试聊沙盒:和真实工具同名同参数,按真实话术模板回复,但只改内存里的一张沙盒单次补货单。
不下发取数端任务、不查 DMS、不建单、不发企微、不写补货单表。库存数据(sample_item):
1. 最近一张真实补货单里有这个零件就用它的查询数据(只读);
2. 没有就按零件号生成一份固定的示例数据。
流程和真实的一样分两段:回「订」→ 假装建单(待提交)→ 回「确认提交」→ 假装提交并回执。
零件号是否出自原话由框架(guards)把关,试聊里同样生效。
"""
from __future__ import annotations
import zlib
from ....core import clock, db
from ....core.db import select
from ....models import lines_t
from ....services import texts
from ... import AgentTool, SandboxBox, ToolResult
from .. import planner
from ..service import STAGE_CN, explicit_submit, svc
STATE_KEY = "restock" # box.state 里沙盒单次补货的键
LINK = "(试聊演练,没有单据链接)"
def state(box: SandboxBox) -> dict:
return box.state.setdefault(STATE_KEY, {"status": "", "doc": "", "lines": [], "source": "", "order_no": ""})
def t(key: str, **kw) -> str:
return texts.render(f"restock.{key}", **kw)
def sample_item(sid: int, part_no: str) -> tuple[dict, str]:
"""试聊用的零件数据:(和 restock.quote 返回的 item 同结构, 数据来源说明)。"""
r = db.one(select(lines_t).where(lines_t.c.store_id == sid, lines_t.c.part_no == part_no)
.order_by(lines_t.c.id.desc()).limit(1))
if r and not r["error"]:
return ({"part_no": part_no, "name": r["name"], "stock": r["stock"], "trans_shipped": r["trans_shipped"],
"unreceived": r["unreceived"], "mad": r["mad"], "daily_surplus": r["cap"],
"unit_price": r["unit_price"], "warehouses": db.jload(r["wh"], {}) or {"GTMC广州": 0, "华南GTMC": 30},
"national_queried": True}, "最近一张真实补货单里的查询数据")
h = zlib.crc32(part_no.encode()) % 100 # 同一零件每次生成的示例数据一样
return ({"part_no": part_no, "name": "示例零件", "stock": h % 7, "trans_shipped": h % 3, "unreceived": 0,
"mad": round(h / 7, 1), "daily_surplus": 5 + h % 20, "unit_price": 10 + h,
"warehouses": {"GTMC广州": h % 2 * 40, "华南GTMC": 100 + h}, "national_queried": True}, "示例数据")
def tools(box: SandboxBox) -> list[AgentTool]:
from .single import TOOLS, multi_parts, once_per_sentence, one_only_text
sid = box.store_id
async def single_restock(_sid, actor, target, part_no: str = "", qty: int = 0) -> ToolResult:
"""和真实流程一致:只报了价(待确认)→ 旧报价作废、按新零件报价;已建单待确认提交 → 不新建。
一句话多个零件只处理一个,其余拼提示(同一句话第二次调用不执行)。"""
again = once_per_sentence(actor)
if again:
return again
st = state(box)
text = actor.extra.get("text", "")
parts, skipped = multi_parts(text)
if len(parts) >= 2 and svc.single_cfg(sid).multi_enabled:
# 批量补货:按真实话术回「收到」和查询汇总(示例数据),但试聊里没有单据页,不建单
cfg = svc.cfg(sid)
box.say(t("msg_multi_querying", parts=parts, skipped=skipped, n=len(parts), eta=svc.multi_eta(sid, len(parts)),
link=LINK))
lines = [planner.plan_multi(sample_item(sid, e["part_no"])[0], e["qty"], cfg.in_transit_field) for e in parts]
s = planner.summary(lines)
box.say(t("msg_multi_quote", s=s, n=len(lines), bad=[l.to_dict() for l in lines if l.blocked], link=LINK))
return ToolResult("试聊:批量补货已回复查询汇总(真实环境会发单据页链接,在页面上建单 / 提交)")
part_no, qty = (part_no or "").strip().upper(), int(qty or 0)
def reply(msg: str, started: bool) -> None:
tail = one_only_text(sid, text, part_no, started)
box.say(f"{msg}\n\n{tail}" if tail else msg)
if st["status"] == "awaiting_submit":
ln = st["lines"][0]
msg = t("msg_single_pending", stage=STAGE_CN[st["status"]], status=st["status"], doc=st["doc"],
order_no=st["order_no"], owner=actor.name, name=ln.name, part_no=ln.part_no, qty=ln.final_qty)
reply(msg, False)
return ToolResult(msg)
if not part_no or qty <= 0 or qty > svc.single_cfg(sid).max_qty:
msg = (t("msg_single_usage") if not part_no or qty <= 0 else
f"{part_no} 要 {qty} 个,超过单次补货上限 {svc.single_cfg(sid).max_qty} 个,请确认数量")
reply(msg, False)
return ToolResult(msg)
prev = ""
if st["status"] == "awaiting_confirm": # 只报了价:作废旧报价
old = st["lines"][0]
prev = t("msg_single_prev_closed", reason="quote", doc=st["doc"], order_no="", status_cn="",
owner=actor.name, name=old.name, part_no=old.part_no, qty=old.final_qty)
st["status"] = "superseded"
msg = t("msg_single_querying", part_no=part_no, qty=qty)
reply(f"{prev}\n\n{msg}" if prev else msg, True)
cfg = svc.cfg(sid)
it, src = sample_item(sid, part_no)
ln = planner.plan_single(it, qty, cfg.in_transit_field)
st.update(doc=f"SANDBOX-{clock.now():%Y%m%d}", lines=[ln], source=src, order_no="",
status="awaiting_confirm" if ln.orderable else "done")
if ln.orderable:
box.say(t("msg_single_quote", l=ln.to_dict(), requested=qty, wh=planner.wh_cn(ln.wh),
in_transit_label=planner.IN_TRANSIT_LABEL.get(cfg.in_transit_field, "在途")))
else:
box.say(t("msg_single_not_orderable", l=ln.to_dict(), requested=qty))
return ToolResult("已回复查询结果")
async def submit_order(_sid, actor, target) -> ToolResult:
st = state(box)
ln = st["lines"][0] if st["lines"] else None
if not explicit_submit(actor.extra.get("text", "")):
msg = (t("msg_submit_need_explicit", order_no=st["order_no"], owner=actor.name)
if st["status"] == "awaiting_submit" else t("msg_submit_not_ready", doc="", stage="", status=""))
box.say(msg)
return ToolResult(msg)
if st["status"] == "awaiting_submit" and ln:
box.say(t("msg_submitting", order_no=st["order_no"], by=actor.name, via_cn="企微群里回复", kind="single"))
st["status"] = "done"
box.say(t("msg_po_submitted", kind="single", order_no=st["order_no"],
lines=[{"part_no": ln.part_no, "name": ln.name, "qty": ln.final_qty,
"amount": ln.final_qty * ln.unit_price}],
count=1, qty=ln.final_qty, amount=ln.final_qty * ln.unit_price, by=actor.name,
confirmed_by=actor.name, already=False, link=LINK))
box.say("(试聊演练:没有真的在 DMS 提交)", kind="note")
return ToolResult("已提交")
msg = t("msg_submit_not_ready", doc=st.get("doc") or "", stage=STAGE_CN.get(st["status"], st["status"] or ""),
status=st["status"] or "") if st["status"] else t("msg_submit_not_ready", doc="", stage="", status="")
box.say(msg)
return ToolResult(msg)
async def confirm_order(_sid, actor, target) -> ToolResult:
st = state(box)
ln = st["lines"][0] if st["lines"] else None
if st["status"] == "awaiting_submit" and ln:
msg = t("msg_submit_need_explicit", order_no=st["order_no"], owner=actor.name)
box.say(msg)
return ToolResult(msg)
if st["status"] != "awaiting_confirm" or not ln:
msg = t("msg_no_pending")
box.say(msg)
return ToolResult(msg)
box.say(t("msg_single_confirmed", l=ln.to_dict()))
st.update(status="awaiting_submit", order_no=f"SANDBOX-PO-{clock.now():%H%M%S}")
box.say(t("msg_po_done", kind="single", order_no=st["order_no"], count=1, qty=ln.final_qty,
amount=ln.final_qty * ln.unit_price, shots=0, fallback="", shot_err="", mismatch="", link=LINK,
can_submit=True, owner=actor.name))
box.say("(试聊演练:没有真的在 DMS 建单,也没有截图;回「确认提交」演练提交)", kind="note")
return ToolResult("已收到,正在创建采购单")
async def cancel_order(_sid, actor, target) -> ToolResult:
st = state(box)
if st["status"] == "awaiting_submit":
st["status"] = "cancelled"
box.say(t("msg_submit_cancelled", order_no=st["order_no"], by=actor.name, kind="single"))
return ToolResult("已标记为先不提交")
if st["status"] != "awaiting_confirm":
msg = t("msg_no_pending")
box.say(msg)
return ToolResult(msg)
st["status"] = "cancelled"
box.say(t("msg_single_cancelled"))
return ToolResult("已取消")
async def single_status(_sid, actor, target) -> ToolResult:
st = state(box)
ln = st["lines"][0] if st["lines"] else None
if st["status"] in ("", "done", "cancelled"):
msg = t("msg_single_status", doc="")
else:
msg = t("msg_single_status", doc=st["doc"], stage=STAGE_CN.get(st["status"], st["status"]),
status=st["status"], order_no=st["order_no"], name=ln.name if ln else "",
part_no=ln.part_no if ln else "", qty=ln.final_qty if ln else "")
box.say(msg)
return ToolResult(msg)
impl = {"single_restock": single_restock, "confirm_order": confirm_order, "submit_order": submit_order,
"cancel_order": cancel_order, "single_status": single_status}
return [AgentTool(x.name, x.description, x.parameters, impl[x.name]) for x in TOOLS if x.name in impl]
def view(box: SandboxBox) -> dict | None:
st = box.state.get(STATE_KEY)
if not st or not st["status"]:
return None
lines = st["lines"]
return {"title": "沙盒单次补货", "doc": st["doc"], "status": st["status"],
"stage": STAGE_CN.get(st["status"], st["status"]), "source": st["source"], "order_no": st["order_no"],
"summary": planner.summary(lines), "lines": [l.to_dict() for l in lines]}