dknowc-dsh 1.4.0 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -19
- package/package.json +3 -3
- package/skills/dknowc-official-doc-writer/README.md +18 -16
- package/skills/dknowc-official-doc-writer/SKILL.md +112 -143
- package/skills/dknowc-official-doc-writer/attribution.json +5 -0
- package/skills/dknowc-official-doc-writer/reference/material_usage_guidance.md +5 -0
- package/skills/dknowc-official-doc-writer/reference/onboarding_scripts.md +18 -8
- package/skills/dknowc-official-doc-writer/reference/output_guide.md +2 -2
- package/skills/dknowc-official-doc-writer/reference/research_notes.md +34 -0
- package/skills/dknowc-official-doc-writer/reference/review_checklist.md +2 -9
- package/skills/dknowc-official-doc-writer/reference/sample_trace_report.html +38 -18
- package/skills/dknowc-official-doc-writer/reference/search_guide.md +100 -33
- package/skills/dknowc-official-doc-writer/reference/search_intro.md +6 -6
- package/skills/dknowc-official-doc-writer/reference/search_policy.md +77 -55
- package/skills/dknowc-official-doc-writer/reference/task_router.md +6 -6
- package/skills/dknowc-official-doc-writer/scripts/api_key.py +41 -14
- package/skills/dknowc-official-doc-writer/scripts/attribution.py +60 -0
- package/skills/dknowc-official-doc-writer/scripts/build_trace_json.py +288 -0
- package/skills/dknowc-official-doc-writer/scripts/check_materials.py +265 -0
- package/skills/dknowc-official-doc-writer/scripts/deep_convert.py +235 -0
- package/skills/dknowc-official-doc-writer/scripts/deep_query.py +333 -0
- package/skills/dknowc-official-doc-writer/scripts/dkag_search.py +13 -4
- package/skills/dknowc-official-doc-writer/scripts/extract_reference.py +245 -0
- package/skills/dknowc-official-doc-writer/scripts/format_document.py +106 -18
- package/skills/dknowc-official-doc-writer/scripts/initialize.py +13 -7
- package/skills/dknowc-official-doc-writer/scripts/mcp_convert.py +272 -0
- package/skills/dknowc-official-doc-writer/scripts/mcp_direct.py +257 -143
- package/skills/dknowc-official-doc-writer/scripts/merge_search_results.py +72 -8
- package/skills/dknowc-official-doc-writer/scripts/outline_reference.py +14 -4
- package/skills/dknowc-official-doc-writer/scripts/prose_lint.py +6 -1
- package/skills/dknowc-official-doc-writer/scripts/register.mjs +122 -50
- package/skills/dknowc-official-doc-writer/scripts/render_trace_html.py +238 -94
- package/skills/dknowc-official-doc-writer/scripts/source_note_html.py +11 -2
- package/skills/dknowc-official-doc-writer/scripts/template_generator.py +13 -0
- package/skills/dknowc-ppt-assistant/README.md +14 -10
- package/skills/dknowc-ppt-assistant/SKILL.md +33 -15
- package/skills/dknowc-ppt-assistant/attribution.json +5 -0
- package/skills/dknowc-ppt-assistant/references/material_usage.md +9 -5
- package/skills/dknowc-ppt-assistant/references/onboarding_scripts.md +14 -2
- package/skills/dknowc-ppt-assistant/references/sample_trace_report.html +123 -115
- package/skills/dknowc-ppt-assistant/references/search_intro.md +1 -1
- package/skills/dknowc-ppt-assistant/references/svg-authoring.md +1 -1
- package/skills/dknowc-ppt-assistant/scripts/api_key.py +41 -14
- package/skills/dknowc-ppt-assistant/scripts/attribution.py +60 -0
- package/skills/dknowc-ppt-assistant/scripts/initialize.py +5 -3
- package/skills/dknowc-ppt-assistant/scripts/mcp_convert.py +188 -0
- package/skills/dknowc-ppt-assistant/scripts/register_key.mjs +184 -94
- package/skills/dknowc-ppt-assistant/scripts/render_trace_html.py +141 -121
- package/skills/dknowc-ppt-assistant/scripts/trusted_search.py +33 -3
- package/skills/dknowc-ppt-assistant/workflows/generate-pptx.md +15 -17
- package/skills/dknowc-trusted-search/README.md +27 -23
- package/skills/dknowc-trusted-search/SKILL.md +213 -141
- package/skills/dknowc-trusted-search/attribution.json +5 -0
- package/skills/dknowc-trusted-search/reference/onboarding_scripts.md +17 -7
- package/skills/dknowc-trusted-search/reference/sample_trace_report.html +129 -521
- package/skills/dknowc-trusted-search/scripts/api_key.py +41 -14
- package/skills/dknowc-trusted-search/scripts/attribution.py +61 -0
- package/skills/dknowc-trusted-search/scripts/chart_embed.py +350 -0
- package/skills/dknowc-trusted-search/scripts/deep_query.py +26 -5
- package/skills/dknowc-trusted-search/scripts/initialize.py +19 -27
- package/skills/dknowc-trusted-search/scripts/mcp_convert.py +189 -0
- package/skills/dknowc-trusted-search/scripts/merge_search_results.py +272 -0
- package/skills/dknowc-trusted-search/scripts/register_key.mjs +151 -45
- package/skills/dknowc-trusted-search/scripts/render_trace_html.py +340 -129
- package/skills/dknowc-trusted-search/scripts/trusted_search.py +28 -28
- package/src/index.js +2 -7
- package/skills/dknowc-ppt-assistant/scripts/adapt_mcp_result.py +0 -279
- package/skills/dknowc-trusted-consulting/README.md +0 -63
- package/skills/dknowc-trusted-consulting/SKILL.md +0 -241
- package/skills/dknowc-trusted-consulting/reference/consult_intro.md +0 -47
- package/skills/dknowc-trusted-consulting/reference/onboarding_scripts.md +0 -132
- package/skills/dknowc-trusted-consulting/reference/sample_consult_answer.md +0 -31
- package/skills/dknowc-trusted-consulting/reference/sample_trace_report.html +0 -867
- package/skills/dknowc-trusted-consulting/scripts/adapt_mcp_result.py +0 -283
- package/skills/dknowc-trusted-consulting/scripts/api_key.py +0 -41
- package/skills/dknowc-trusted-consulting/scripts/gov_chat.py +0 -508
- package/skills/dknowc-trusted-consulting/scripts/initialize.py +0 -123
- package/skills/dknowc-trusted-consulting/scripts/mcp_direct.py +0 -166
- package/skills/dknowc-trusted-consulting/scripts/register_key.mjs +0 -281
- package/skills/dknowc-trusted-consulting/scripts/render_trace_html.py +0 -2534
- package/skills/dknowc-trusted-search/scripts/adapt_mcp_result.py +0 -261
- package/skills/dknowc-trusted-search/scripts/render_policy_visualization.py +0 -894
|
@@ -1,508 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env python3
|
|
2
|
-
"""深知可信咨询调用脚本。
|
|
3
|
-
|
|
4
|
-
固定调用统一接口 credibleChat 能力;不提供 credibleRecall 路径。
|
|
5
|
-
"""
|
|
6
|
-
|
|
7
|
-
import argparse
|
|
8
|
-
import json
|
|
9
|
-
import os
|
|
10
|
-
import re
|
|
11
|
-
import socket
|
|
12
|
-
import sys
|
|
13
|
-
import urllib.error
|
|
14
|
-
import urllib.request
|
|
15
|
-
import uuid
|
|
16
|
-
from pathlib import Path
|
|
17
|
-
from typing import Any, Dict, Iterable, Optional
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
DEFAULT_ENDPOINT = "https://open.dknowc.cn/chat/trusted/unification"
|
|
21
|
-
SKILL_ROOT = Path(__file__).resolve().parent.parent
|
|
22
|
-
# 工作区根:dsh 场景通过环境变量 DKNWOC_WS_ROOT 指向会话工作区,未设置时回退到 cwd
|
|
23
|
-
import os as _os
|
|
24
|
-
_ws = _os.environ.get("DKNWOC_WS_ROOT")
|
|
25
|
-
if not _ws:
|
|
26
|
-
# dsh 会话隔离:每会话独立产物目录 <工作区>/dknowc-output/<DSH_SESSION_ID前8位>/,
|
|
27
|
-
# 多会话共用同一工作区时互不混杂;非 dsh 环境回退为工作区本身。
|
|
28
|
-
_sid = _os.environ.get("DSH_SESSION_ID", "")
|
|
29
|
-
_ws = str(Path(_os.getcwd()) / "dknowc-output" / (_sid[:8] if _sid else "_default"))
|
|
30
|
-
WS_ROOT = Path(_ws).resolve()
|
|
31
|
-
SEARCH_RESULTS_DIR = WS_ROOT / "official-docs" / "search-results"
|
|
32
|
-
DEFAULTS = {
|
|
33
|
-
"area": "",
|
|
34
|
-
"session_id": "",
|
|
35
|
-
"request_id": "",
|
|
36
|
-
"interpretation_model": "autoModel",
|
|
37
|
-
"safe_answer_type": "active",
|
|
38
|
-
"safe_answer_scope": "all",
|
|
39
|
-
"credible_chat_scope": "all",
|
|
40
|
-
"search_mechanism": "autoSearch",
|
|
41
|
-
"material": True,
|
|
42
|
-
"recommended_questions": False,
|
|
43
|
-
"item": True,
|
|
44
|
-
"policy": True,
|
|
45
|
-
"traceurl": False,
|
|
46
|
-
"stream": True,
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
def resolve_output_json(output_path: str) -> Path:
|
|
51
|
-
"""把咨询结果 JSON 落到本 Skill 的 official-docs/search-results/ 工作区。
|
|
52
|
-
|
|
53
|
-
裸文件名进 search-results/;带子路径的相对路径按 SKILL_ROOT 解析,
|
|
54
|
-
因此 official-docs/search-results/xxx.json 这类写法也可直接使用。
|
|
55
|
-
"""
|
|
56
|
-
raw = Path(output_path).expanduser()
|
|
57
|
-
if raw.is_absolute():
|
|
58
|
-
resolved = raw.resolve()
|
|
59
|
-
elif raw.parent == Path("."):
|
|
60
|
-
resolved = (SEARCH_RESULTS_DIR / raw.name).resolve()
|
|
61
|
-
else:
|
|
62
|
-
resolved = (SKILL_ROOT / raw).resolve()
|
|
63
|
-
if resolved.suffix.lower() != ".json":
|
|
64
|
-
resolved = resolved.with_suffix(".json")
|
|
65
|
-
return resolved
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
MAAS_LOGIN_URL = "https://platform.dknowc.cn/auth/#/login"
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
def _error_user_message(code: int) -> str:
|
|
72
|
-
"""按接口错误码返回给用户的固定话术(Agent 原样转述);口径见 reference/onboarding_scripts.md。"""
|
|
73
|
-
if code == 401:
|
|
74
|
-
return "访问密钥校验没通过(密钥可能已失效),我重新获取一下密钥;还不行的话需要重新验证手机号。"
|
|
75
|
-
if code == 403:
|
|
76
|
-
return f"当前密钥没有问答权限(可能类型不符或已变更)。到 {MAAS_LOGIN_URL} 查看密钥权限,或重新验证手机号获取新密钥。"
|
|
77
|
-
if code in (402, 429):
|
|
78
|
-
return f"咨询调不动,很可能是额度用完了:到 {MAAS_LOGIN_URL} 看一下额度,完成实名认证可以领 100 元体验金。"
|
|
79
|
-
if code >= 500:
|
|
80
|
-
return "咨询服务暂时异常,我稍后再试;持续异常的话我按已有知识先答,并标注“未联网核验”。"
|
|
81
|
-
return ""
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
def _print_error_with_message(prefix: str, code: Optional[int] = None) -> None:
|
|
85
|
-
"""打印错误与固定话术:Agent 优先向用户转述 user_message 行。"""
|
|
86
|
-
print(prefix, file=sys.stderr)
|
|
87
|
-
user_message = _error_user_message(code) if code is not None else ""
|
|
88
|
-
if not user_message:
|
|
89
|
-
user_message = "咨询暂时没连上(网络波动),稍等我再试一次;持续失败的话我按已有知识先答,并标注“未联网核验”。"
|
|
90
|
-
print(f"user_message:{user_message}", file=sys.stderr)
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
def _as_bool(value: Optional[str], default: bool = False) -> bool:
|
|
94
|
-
if value is None:
|
|
95
|
-
return default
|
|
96
|
-
value = value.strip()
|
|
97
|
-
if not value:
|
|
98
|
-
return default
|
|
99
|
-
return value.lower() in {"1", "true", "yes", "y", "on"}
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
def _pick(*values: Optional[str]) -> str:
|
|
103
|
-
for value in values:
|
|
104
|
-
if value:
|
|
105
|
-
return value.strip()
|
|
106
|
-
return ""
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
def _build_payload(args: argparse.Namespace) -> Dict[str, Any]:
|
|
110
|
-
material = args.material or bool(DEFAULTS["material"])
|
|
111
|
-
if args.no_material:
|
|
112
|
-
material = False
|
|
113
|
-
payload: Dict[str, Any] = {
|
|
114
|
-
"input": args.input,
|
|
115
|
-
"safeAnswerType": args.safe_answer_type or str(DEFAULTS["safe_answer_type"]),
|
|
116
|
-
"safeAnswerScope": args.safe_answer_scope or str(DEFAULTS["safe_answer_scope"]),
|
|
117
|
-
"knowledgeServiceType": "credibleChat",
|
|
118
|
-
"credibleChatScope": args.credible_chat_scope or str(DEFAULTS["credible_chat_scope"]),
|
|
119
|
-
"searchMechanism": args.search_mechanism or str(DEFAULTS["search_mechanism"]),
|
|
120
|
-
"interpretationModel": args.interpretation_model or str(DEFAULTS["interpretation_model"]),
|
|
121
|
-
"material": material,
|
|
122
|
-
"recommendedQuestions": args.recommended_questions or bool(DEFAULTS["recommended_questions"]),
|
|
123
|
-
"item": False if args.no_item else args.item or bool(DEFAULTS["item"]),
|
|
124
|
-
"policy": False if args.no_policy else args.policy or bool(DEFAULTS["policy"]),
|
|
125
|
-
"traceurl": args.traceurl or bool(DEFAULTS["traceurl"]),
|
|
126
|
-
"stream": args.stream or (not args.no_stream and bool(DEFAULTS["stream"])),
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
if args.show_reasoning:
|
|
130
|
-
payload["interpretationModel"] = "deepModel"
|
|
131
|
-
|
|
132
|
-
request_id = args.request_id or str(DEFAULTS["request_id"])
|
|
133
|
-
if args.auto_request_id and not request_id:
|
|
134
|
-
request_id = uuid.uuid4().hex + uuid.uuid4().hex[:8]
|
|
135
|
-
|
|
136
|
-
optional = {
|
|
137
|
-
"area": args.area or str(DEFAULTS["area"]),
|
|
138
|
-
"requestId": request_id,
|
|
139
|
-
"sessionId": args.session_id or str(DEFAULTS["session_id"]),
|
|
140
|
-
}
|
|
141
|
-
for key, value in optional.items():
|
|
142
|
-
if value:
|
|
143
|
-
payload[key] = value
|
|
144
|
-
|
|
145
|
-
return payload
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
def _read_sse_response(resp: Any) -> str:
|
|
149
|
-
chunks = []
|
|
150
|
-
while True:
|
|
151
|
-
raw_line = resp.readline()
|
|
152
|
-
if not raw_line:
|
|
153
|
-
break
|
|
154
|
-
line = raw_line.decode("utf-8", errors="replace")
|
|
155
|
-
chunks.append(line)
|
|
156
|
-
if line.strip() in {"data: [DONE]", "[DONE]"}:
|
|
157
|
-
break
|
|
158
|
-
return "".join(chunks).replace("\x00", "")
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
def _post(url: str, api_key: str, payload: Dict[str, Any], timeout: int) -> str:
|
|
162
|
-
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
|
163
|
-
req = urllib.request.Request(url, data=data, method="POST")
|
|
164
|
-
req.add_header("api-key", api_key)
|
|
165
|
-
req.add_header("Content-Type", "application/json")
|
|
166
|
-
|
|
167
|
-
try:
|
|
168
|
-
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
169
|
-
if payload.get("stream"):
|
|
170
|
-
return _read_sse_response(resp)
|
|
171
|
-
return resp.read().decode("utf-8", errors="replace").replace("\x00", "")
|
|
172
|
-
except urllib.error.HTTPError as e:
|
|
173
|
-
detail = e.read().decode("utf-8", errors="ignore")
|
|
174
|
-
_print_error_with_message(f"错误:HTTP {e.code} {detail or e.reason}", e.code)
|
|
175
|
-
sys.exit(1)
|
|
176
|
-
except urllib.error.URLError as e:
|
|
177
|
-
_print_error_with_message(f"错误:网络请求失败 - {e.reason}")
|
|
178
|
-
sys.exit(1)
|
|
179
|
-
except socket.timeout:
|
|
180
|
-
_print_error_with_message("错误:接口流式响应读取超时。请确认接口是否持续输出 SSE 数据,或适当增大 --timeout。")
|
|
181
|
-
sys.exit(1)
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
class _StreamingCleaner:
|
|
185
|
-
def __init__(self) -> None:
|
|
186
|
-
self._buffer = ""
|
|
187
|
-
self._hold_chars = 512
|
|
188
|
-
|
|
189
|
-
def feed(self, text: str) -> str:
|
|
190
|
-
self._buffer += text
|
|
191
|
-
if len(self._buffer) <= self._hold_chars:
|
|
192
|
-
return ""
|
|
193
|
-
cut = len(self._buffer) - self._hold_chars
|
|
194
|
-
|
|
195
|
-
last_tag_start = self._buffer.rfind("<", 0, cut)
|
|
196
|
-
if last_tag_start != -1:
|
|
197
|
-
next_tag_end = self._buffer.find(">", last_tag_start)
|
|
198
|
-
if next_tag_end == -1 or next_tag_end >= cut:
|
|
199
|
-
cut = last_tag_start
|
|
200
|
-
|
|
201
|
-
last_citation_start = max(
|
|
202
|
-
self._buffer.rfind("[^", 0, cut),
|
|
203
|
-
self._buffer.rfind("[", 0, cut),
|
|
204
|
-
)
|
|
205
|
-
if last_citation_start != -1:
|
|
206
|
-
next_citation_end = self._buffer.find("]", last_citation_start)
|
|
207
|
-
if next_citation_end == -1 or next_citation_end >= cut:
|
|
208
|
-
cut = last_citation_start
|
|
209
|
-
|
|
210
|
-
safe, self._buffer = self._buffer[:cut], self._buffer[cut:]
|
|
211
|
-
return _format_answer_content(safe)
|
|
212
|
-
|
|
213
|
-
def finish(self) -> str:
|
|
214
|
-
text = _format_answer_content(self._buffer)
|
|
215
|
-
self._buffer = ""
|
|
216
|
-
return text
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
def _post_streaming_to_stdout(url: str, api_key: str, payload: Dict[str, Any], timeout: int) -> None:
|
|
220
|
-
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
|
221
|
-
req = urllib.request.Request(url, data=data, method="POST")
|
|
222
|
-
req.add_header("api-key", api_key)
|
|
223
|
-
req.add_header("Content-Type", "application/json")
|
|
224
|
-
|
|
225
|
-
cleaner = _StreamingCleaner()
|
|
226
|
-
trace_url = ""
|
|
227
|
-
wrote_content = False
|
|
228
|
-
|
|
229
|
-
try:
|
|
230
|
-
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
231
|
-
while True:
|
|
232
|
-
raw_line = resp.readline()
|
|
233
|
-
if not raw_line:
|
|
234
|
-
break
|
|
235
|
-
line = raw_line.decode("utf-8", errors="replace").replace("\x00", "").strip()
|
|
236
|
-
if not line.startswith("data:"):
|
|
237
|
-
continue
|
|
238
|
-
chunk = line[5:].strip()
|
|
239
|
-
if chunk == "[DONE]":
|
|
240
|
-
break
|
|
241
|
-
try:
|
|
242
|
-
obj = json.loads(chunk)
|
|
243
|
-
except json.JSONDecodeError:
|
|
244
|
-
continue
|
|
245
|
-
|
|
246
|
-
if isinstance(obj.get("traceUrl"), str):
|
|
247
|
-
trace_url = obj["traceUrl"].strip()
|
|
248
|
-
|
|
249
|
-
piece = _extract_piece(obj)
|
|
250
|
-
if not piece:
|
|
251
|
-
continue
|
|
252
|
-
|
|
253
|
-
cleaned = cleaner.feed(piece)
|
|
254
|
-
if cleaned:
|
|
255
|
-
print(cleaned, end="", flush=True)
|
|
256
|
-
wrote_content = True
|
|
257
|
-
|
|
258
|
-
tail = cleaner.finish()
|
|
259
|
-
if tail:
|
|
260
|
-
print(tail, end="", flush=True)
|
|
261
|
-
wrote_content = True
|
|
262
|
-
if wrote_content:
|
|
263
|
-
print()
|
|
264
|
-
if trace_url:
|
|
265
|
-
print("\n可信溯源报告")
|
|
266
|
-
print(trace_url)
|
|
267
|
-
except urllib.error.HTTPError as e:
|
|
268
|
-
detail = e.read().decode("utf-8", errors="ignore")
|
|
269
|
-
_print_error_with_message(f"错误:HTTP {e.code} {detail or e.reason}", e.code)
|
|
270
|
-
sys.exit(1)
|
|
271
|
-
except urllib.error.URLError as e:
|
|
272
|
-
_print_error_with_message(f"错误:网络请求失败 - {e.reason}")
|
|
273
|
-
sys.exit(1)
|
|
274
|
-
except socket.timeout:
|
|
275
|
-
_print_error_with_message("错误:接口流式响应读取超时。请确认接口是否持续输出 SSE 数据,或适当增大 --timeout。")
|
|
276
|
-
sys.exit(1)
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
def _iter_sse_payloads(text: str) -> Iterable[Dict[str, Any]]:
|
|
280
|
-
for raw_line in text.splitlines():
|
|
281
|
-
line = raw_line.strip()
|
|
282
|
-
if not line.startswith("data:"):
|
|
283
|
-
continue
|
|
284
|
-
chunk = line[5:].strip()
|
|
285
|
-
if chunk == "[DONE]":
|
|
286
|
-
break
|
|
287
|
-
try:
|
|
288
|
-
yield json.loads(chunk)
|
|
289
|
-
except json.JSONDecodeError:
|
|
290
|
-
continue
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
def _merge_sse_result(text: str) -> Dict[str, Any]:
|
|
294
|
-
result: Dict[str, Any] = {}
|
|
295
|
-
resp: Dict[str, Any] = {}
|
|
296
|
-
content_parts = []
|
|
297
|
-
reasoning_parts = []
|
|
298
|
-
|
|
299
|
-
for obj in _iter_sse_payloads(text):
|
|
300
|
-
for key in ("requestId", "sessionId", "safeType", "knowledgeScope", "created", "area", "traceUrl"):
|
|
301
|
-
if key in obj and key not in result:
|
|
302
|
-
result[key] = obj[key]
|
|
303
|
-
|
|
304
|
-
for key in ("referenceMaterials", "recommendationItems", "policyFiles"):
|
|
305
|
-
if key in obj and key not in result:
|
|
306
|
-
result[key] = obj[key]
|
|
307
|
-
|
|
308
|
-
chunk_resp = obj.get("resp")
|
|
309
|
-
if isinstance(chunk_resp, dict):
|
|
310
|
-
for key in ("waitText", "areaTip"):
|
|
311
|
-
if key in chunk_resp and key not in resp:
|
|
312
|
-
resp[key] = chunk_resp[key]
|
|
313
|
-
content = chunk_resp.get("content")
|
|
314
|
-
if isinstance(content, str):
|
|
315
|
-
content_parts.append(content)
|
|
316
|
-
reasoning = chunk_resp.get("reasoning_content")
|
|
317
|
-
if isinstance(reasoning, str):
|
|
318
|
-
reasoning_parts.append(reasoning)
|
|
319
|
-
|
|
320
|
-
choices = obj.get("choices")
|
|
321
|
-
if isinstance(choices, list) and choices:
|
|
322
|
-
delta = choices[0].get("delta", {})
|
|
323
|
-
if isinstance(delta, dict):
|
|
324
|
-
for key in ("waitText", "areaTip"):
|
|
325
|
-
if key in delta and key not in resp:
|
|
326
|
-
resp[key] = delta[key]
|
|
327
|
-
content = delta.get("content")
|
|
328
|
-
if isinstance(content, str):
|
|
329
|
-
content_parts.append(content)
|
|
330
|
-
reasoning = delta.get("reasoning_content")
|
|
331
|
-
if isinstance(reasoning, str):
|
|
332
|
-
reasoning_parts.append(reasoning)
|
|
333
|
-
|
|
334
|
-
if content_parts:
|
|
335
|
-
resp["content"] = "".join(content_parts)
|
|
336
|
-
if reasoning_parts:
|
|
337
|
-
resp["reasoning_content"] = "".join(reasoning_parts)
|
|
338
|
-
if resp:
|
|
339
|
-
result["resp"] = resp
|
|
340
|
-
return result
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
def _normalize_result(text: str) -> Dict[str, Any]:
|
|
344
|
-
stripped = text.strip()
|
|
345
|
-
if not stripped:
|
|
346
|
-
return {"resp": {"content": ""}}
|
|
347
|
-
if "data:" in stripped:
|
|
348
|
-
return _merge_sse_result(stripped)
|
|
349
|
-
try:
|
|
350
|
-
body = json.loads(stripped)
|
|
351
|
-
except json.JSONDecodeError:
|
|
352
|
-
return {"resp": {"content": stripped}}
|
|
353
|
-
if isinstance(body, dict):
|
|
354
|
-
return body
|
|
355
|
-
return {"resp": {"content": body}}
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
def _strip_html(text: str) -> str:
|
|
359
|
-
return re.sub(r"<[^>]+>", "", text)
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
def _format_answer_content(text: str) -> str:
|
|
363
|
-
cleaned = _strip_html(text)
|
|
364
|
-
return re.sub(r"\[\^?\d+\^?\]", "", cleaned)
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
def _print_trace_report(result: Dict[str, Any]) -> None:
|
|
368
|
-
trace_url = result.get("traceUrl")
|
|
369
|
-
if isinstance(trace_url, str) and trace_url.strip():
|
|
370
|
-
print("\n可信溯源报告")
|
|
371
|
-
print(trace_url.strip())
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
def _print_summary(result: Dict[str, Any], show_reasoning: bool) -> None:
|
|
375
|
-
resp = result.get("resp", {})
|
|
376
|
-
if isinstance(resp, dict):
|
|
377
|
-
if resp.get("waitText"):
|
|
378
|
-
print(resp["waitText"])
|
|
379
|
-
if resp.get("areaTip"):
|
|
380
|
-
print(resp["areaTip"])
|
|
381
|
-
|
|
382
|
-
content = resp.get("content")
|
|
383
|
-
if content:
|
|
384
|
-
print(_format_answer_content(content))
|
|
385
|
-
|
|
386
|
-
reasoning = resp.get("reasoning_content")
|
|
387
|
-
if show_reasoning and reasoning:
|
|
388
|
-
print(f"\n模型思考过程:\n{reasoning}")
|
|
389
|
-
elif resp:
|
|
390
|
-
print(resp)
|
|
391
|
-
|
|
392
|
-
_print_trace_report(result)
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
def _print_result(text: str, raw: bool, json_only: bool, show_reasoning: bool, output: Optional[str] = None) -> None:
|
|
396
|
-
result = _normalize_result(text)
|
|
397
|
-
|
|
398
|
-
if json_only:
|
|
399
|
-
payload = {"success": True, "data": result}
|
|
400
|
-
if output:
|
|
401
|
-
output_path = resolve_output_json(output)
|
|
402
|
-
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
403
|
-
output_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
404
|
-
print(f"已保存咨询结果 JSON:{_rel_to_ws(output_path)}")
|
|
405
|
-
return
|
|
406
|
-
print(json.dumps(payload, ensure_ascii=False, indent=2))
|
|
407
|
-
return
|
|
408
|
-
|
|
409
|
-
_print_summary(result, show_reasoning)
|
|
410
|
-
if raw:
|
|
411
|
-
print("\n=== RAW_RESPONSE_START ===")
|
|
412
|
-
print(text.strip())
|
|
413
|
-
print("=== RAW_RESPONSE_END ===")
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
def _extract_piece(obj: Dict[str, Any]) -> str:
|
|
417
|
-
choices = obj.get("choices")
|
|
418
|
-
if isinstance(choices, list) and choices:
|
|
419
|
-
delta = choices[0].get("delta", {})
|
|
420
|
-
if isinstance(delta, dict):
|
|
421
|
-
for key in ("content", "reasoning_content", "areaTip", "waitText"):
|
|
422
|
-
value = delta.get(key)
|
|
423
|
-
if isinstance(value, str):
|
|
424
|
-
return value
|
|
425
|
-
|
|
426
|
-
resp = obj.get("resp")
|
|
427
|
-
if isinstance(resp, dict):
|
|
428
|
-
content = resp.get("content")
|
|
429
|
-
if isinstance(content, str):
|
|
430
|
-
return content
|
|
431
|
-
|
|
432
|
-
content = obj.get("content")
|
|
433
|
-
if isinstance(content, str):
|
|
434
|
-
return content
|
|
435
|
-
return ""
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
def main() -> None:
|
|
439
|
-
parser = argparse.ArgumentParser(description="深知可信咨询 credibleChat 调用脚本")
|
|
440
|
-
parser.add_argument("input", help="用户政务问题")
|
|
441
|
-
parser.add_argument("--endpoint", help="覆盖接口地址")
|
|
442
|
-
parser.add_argument("--area", help="覆盖地域")
|
|
443
|
-
parser.add_argument("--session-id", help="覆盖 sessionId")
|
|
444
|
-
parser.add_argument("--request-id", help="覆盖 requestId")
|
|
445
|
-
parser.add_argument("--auto-request-id", action="store_true", help="未传 requestId 时自动生成")
|
|
446
|
-
parser.add_argument("--safe-answer-scope", choices=["none", "all", "risk"], help="覆盖安全代答范围")
|
|
447
|
-
parser.add_argument("--safe-answer-type", choices=["active", "conservative"], help="覆盖安全代答模式")
|
|
448
|
-
parser.add_argument("--credible-chat-scope", choices=["onlyNorms", "needNorms", "all"], help="覆盖可信问答范围")
|
|
449
|
-
parser.add_argument("--search-mechanism", choices=["quickSearch", "autoSearch", "deepSearch"], help="覆盖搜索机制")
|
|
450
|
-
parser.add_argument("--interpretation-model", choices=["autoModel", "fastModel", "deepModel"], help="覆盖解读模型")
|
|
451
|
-
parser.add_argument("--material", action="store_true", help="返回参考材料")
|
|
452
|
-
parser.add_argument("--no-material", action="store_true", help="不返回参考材料")
|
|
453
|
-
parser.add_argument("--recommended-questions", action="store_true", help="返回推荐问题")
|
|
454
|
-
parser.add_argument("--item", action="store_true", help="返回办理事项")
|
|
455
|
-
parser.add_argument("--no-item", action="store_true", help="不返回办理事项")
|
|
456
|
-
parser.add_argument("--policy", action="store_true", help="返回政策文件")
|
|
457
|
-
parser.add_argument("--no-policy", action="store_true", help="不返回政策文件")
|
|
458
|
-
parser.add_argument("--traceurl", action="store_true", help="返回可信溯源报告链接")
|
|
459
|
-
parser.add_argument("--stream", action="store_true", help="开启流式返回")
|
|
460
|
-
parser.add_argument("--no-stream", action="store_true", help="关闭流式")
|
|
461
|
-
parser.add_argument("--show-payload", action="store_true", help="打印请求参数")
|
|
462
|
-
parser.add_argument("--dry-run", action="store_true", help="只打印请求参数,不发起请求")
|
|
463
|
-
parser.add_argument("--raw", action="store_true", help="打印原始响应")
|
|
464
|
-
parser.add_argument("--json-only", action="store_true", help="仅输出聚合后的 JSON")
|
|
465
|
-
parser.add_argument("--output", "-o", help="咨询结果 JSON 文件名,写入 official-docs/search-results/(配合 --json-only 使用)")
|
|
466
|
-
parser.add_argument("--show-reasoning", action="store_true", help="显示 deepModel 思考过程,并自动使用 deepModel")
|
|
467
|
-
parser.add_argument("--timeout", type=int, default=90, help="请求超时秒数")
|
|
468
|
-
args = parser.parse_args()
|
|
469
|
-
|
|
470
|
-
endpoint = _pick(
|
|
471
|
-
args.endpoint,
|
|
472
|
-
os.environ.get("DKNOWC_KNOW_ENDPOINT"),
|
|
473
|
-
os.environ.get("DKNOWC_GOV_ZHICHA_ENDPOINT"),
|
|
474
|
-
DEFAULT_ENDPOINT,
|
|
475
|
-
)
|
|
476
|
-
# 环境变量优先,缺失时从 ~/.zshrc 兜底解析(宿主进程读不到 shell 导出变量时不误报缺失)
|
|
477
|
-
try:
|
|
478
|
-
from api_key import resolve_api_key
|
|
479
|
-
api_key, _key_source = resolve_api_key()
|
|
480
|
-
except ImportError:
|
|
481
|
-
api_key = os.environ.get("DKNOWC_API_KEY", "").strip()
|
|
482
|
-
|
|
483
|
-
if not endpoint:
|
|
484
|
-
print("错误:缺少 endpoint,请通过脚本默认值、--endpoint 或环境变量配置。", file=sys.stderr)
|
|
485
|
-
sys.exit(2)
|
|
486
|
-
if not api_key:
|
|
487
|
-
print("错误:缺少 api_key,环境变量 DKNOWC_API_KEY 与 ~/.zshrc 中均未找到。", file=sys.stderr)
|
|
488
|
-
sys.exit(2)
|
|
489
|
-
|
|
490
|
-
payload = _build_payload(args)
|
|
491
|
-
if args.show_payload:
|
|
492
|
-
safe_payload = dict(payload)
|
|
493
|
-
print("=== 请求参数 ===")
|
|
494
|
-
print(json.dumps(safe_payload, ensure_ascii=False, indent=2))
|
|
495
|
-
print()
|
|
496
|
-
if args.dry_run:
|
|
497
|
-
return
|
|
498
|
-
|
|
499
|
-
if payload.get("stream") and not (args.raw or args.json_only or args.show_reasoning):
|
|
500
|
-
_post_streaming_to_stdout(endpoint, api_key, payload, args.timeout)
|
|
501
|
-
return
|
|
502
|
-
|
|
503
|
-
text = _post(endpoint, api_key, payload, args.timeout)
|
|
504
|
-
_print_result(text, args.raw, args.json_only, args.show_reasoning, args.output)
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
if __name__ == "__main__":
|
|
508
|
-
main()
|
|
@@ -1,123 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env python3
|
|
2
|
-
"""深知可信咨询 SkillHub public 版初始化检查。
|
|
3
|
-
|
|
4
|
-
API Key 解析:优先进程环境变量 DKNOWC_API_KEY,缺失时从 ~/.zshrc 兜底解析——
|
|
5
|
-
宿主应用(WorkBuddy 等)的会话进程可能读不到用户 shell 环境变量(启动早于
|
|
6
|
-
key 写入,或宿主不再加载 ~/.zshrc 导出值),盘上已有 key 时不应误报缺失。
|
|
7
|
-
不读取、不写入本地 config.ini 中的 Key。
|
|
8
|
-
"""
|
|
9
|
-
|
|
10
|
-
import json
|
|
11
|
-
import os
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
API_KEY_ENV = "DKNOWC_API_KEY"
|
|
15
|
-
PLACEHOLDER_KEYS = {"", "your_api_key_here", "你的深知可信统一接口 API Key", "你的深知可信咨询 API Key"}
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
def _looks_like_key(value: str) -> bool:
|
|
19
|
-
value = (value or "").strip()
|
|
20
|
-
return value not in PLACEHOLDER_KEYS
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
def _in_dsh() -> bool:
|
|
24
|
-
"""dsh 环境标志:dsh 的 bash 工具会注入 DSH_SHELL=1。"""
|
|
25
|
-
return os.environ.get("DSH_SHELL") == "1"
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
def check_api_key_config():
|
|
29
|
-
if _in_dsh():
|
|
30
|
-
# dsh 场景:优先插件经 shell-env 注入的 DSH_DKNOWC_API_KEY(与 MCP Bearer 同源);
|
|
31
|
-
# 缺失时本地环境变量 / ~/.zshrc 兜底(注册成功自动持久化后、dsh 重启前的窗口期)。
|
|
32
|
-
api_key = os.environ.get("DSH_DKNOWC_API_KEY", "").strip()
|
|
33
|
-
source = "environment"
|
|
34
|
-
if not _looks_like_key(api_key):
|
|
35
|
-
try:
|
|
36
|
-
from api_key import resolve_api_key
|
|
37
|
-
api_key2, source2 = resolve_api_key()
|
|
38
|
-
if _looks_like_key(api_key2):
|
|
39
|
-
api_key, source = api_key2, source2
|
|
40
|
-
except ImportError:
|
|
41
|
-
pass
|
|
42
|
-
if _looks_like_key(api_key):
|
|
43
|
-
note = "dsh 场景:接口经深知可信工作台 MCP 转接(credible_chat),API Key 由 dsh 主进程环境变量 DKNOWC_API_KEY 提供(经 shell-env 显式注入为 DSH_DKNOWC_API_KEY)。"
|
|
44
|
-
if source == "zshrc":
|
|
45
|
-
note = ("dsh 场景:Key 已持久化在 ~/.zshrc(api_key_source=zshrc)。当前 dsh 主进程环境变量尚未加载该 Key——"
|
|
46
|
-
"本会话的 MCP Bearer 认证在启动时已冻结,请经 scripts/mcp_direct.py 直调完成当前任务"
|
|
47
|
-
"(脚本会自动从 ~/.zshrc 解析 Key);重启 dsh 或新开会话后自动恢复正常 MCP 转接。")
|
|
48
|
-
return {
|
|
49
|
-
"api_key_configured": True,
|
|
50
|
-
"api_key_env": f"{API_KEY_ENV} (DSH_DKNOWC_API_KEY)" if source == "environment" else API_KEY_ENV,
|
|
51
|
-
"api_key_source": source,
|
|
52
|
-
"api_key_hint": None,
|
|
53
|
-
"search_ready": True,
|
|
54
|
-
"search_note": note,
|
|
55
|
-
}
|
|
56
|
-
return {
|
|
57
|
-
"api_key_configured": False,
|
|
58
|
-
"api_key_env": API_KEY_ENV,
|
|
59
|
-
"api_key_source": None,
|
|
60
|
-
"api_key_hint": f"未检测到可用的 {API_KEY_ENV}(dsh 主进程环境变量与 ~/.zshrc 中均未找到)。需要先将有效的 API Key 配置到启动 dsh 的环境变量 {API_KEY_ENV}(如 ~/.zshrc),再重启 dsh 或新建会话。",
|
|
61
|
-
"search_ready": False,
|
|
62
|
-
"search_note": f"当前未检测到可用的 {API_KEY_ENV},暂时无法获取深知可信内容。",
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
# 环境变量优先,缺失时从 ~/.zshrc 兜底解析(与深知公文写作 api_key.py 同源)
|
|
66
|
-
try:
|
|
67
|
-
from api_key import resolve_api_key
|
|
68
|
-
api_key, source = resolve_api_key()
|
|
69
|
-
except ImportError:
|
|
70
|
-
api_key = os.environ.get(API_KEY_ENV, "").strip()
|
|
71
|
-
source = "environment" if api_key else ""
|
|
72
|
-
if _looks_like_key(api_key):
|
|
73
|
-
return {
|
|
74
|
-
"api_key_configured": True,
|
|
75
|
-
"api_key_env": API_KEY_ENV,
|
|
76
|
-
"api_key_source": source,
|
|
77
|
-
"api_key_hint": None,
|
|
78
|
-
"search_ready": True,
|
|
79
|
-
"search_note": None,
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
return {
|
|
83
|
-
"api_key_configured": False,
|
|
84
|
-
"api_key_env": API_KEY_ENV,
|
|
85
|
-
"api_key_source": None,
|
|
86
|
-
"api_key_hint": f"本 Skill 需要通过环境变量 {API_KEY_ENV} 调用深知可信统一接口获取可信内容,当前环境变量与 ~/.zshrc 中均未找到有效 Key。请先注册或登录深知可信智能 MaaS 账号获取 API Key,再注入该环境变量。",
|
|
87
|
-
"search_ready": False,
|
|
88
|
-
"search_note": f"当前未检测到可用的 {API_KEY_ENV},暂时无法获取深知可信内容。",
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
def main():
|
|
93
|
-
status = check_api_key_config()
|
|
94
|
-
blocking_issues = []
|
|
95
|
-
if not status["api_key_configured"]:
|
|
96
|
-
blocking_issues.append("api_key_missing")
|
|
97
|
-
|
|
98
|
-
# guide_message:需要可信咨询但 Key 未配置时给用户的引导话术(S1 三段式:价值 / 权益+开通方式 / 退路+样例钩子)。
|
|
99
|
-
# Agent 优先原样转述本话术;完整话术库见 reference/onboarding_scripts.md。
|
|
100
|
-
guide_message = None
|
|
101
|
-
if not status["api_key_configured"]:
|
|
102
|
-
guide_message = (
|
|
103
|
-
"这个问题涉及具体的办事条件和金额口径,凭记忆回答容易过时或者记错地区差异,"
|
|
104
|
-
"答错了会影响办事和决策。开通可信咨询后,答案基于权威文件库原文,"
|
|
105
|
-
"条件、金额、办理路径都带出处、可点开核验。\n"
|
|
106
|
-
"开通是免费的:自带 300 次可信咨询额度,完成实名认证还能再领 100 元体验金。"
|
|
107
|
-
"只需手机号收一次验证码——两步、约 10 秒,不用去网站,剩下的我来办;"
|
|
108
|
-
"手机号仅用于本次验证,不会有营销骚扰。\n"
|
|
109
|
-
"也可以先不开通:我按已有知识先答,并明确标注“未联网核验、口径可能过期”。"
|
|
110
|
-
"想先看看开通后生成的核验报告长什么样,我可以发你一份示例看看。"
|
|
111
|
-
)
|
|
112
|
-
|
|
113
|
-
print(json.dumps({
|
|
114
|
-
**status,
|
|
115
|
-
"blocking_issues": blocking_issues,
|
|
116
|
-
"ready": not blocking_issues,
|
|
117
|
-
"guide_message": guide_message,
|
|
118
|
-
"maas_platform_url": "https://platform.dknowc.cn/auth/#/login",
|
|
119
|
-
}, ensure_ascii=False, indent=2))
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
if __name__ == "__main__":
|
|
123
|
-
main()
|