dknowc-dsh 1.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/LICENSE +21 -0
- package/README.md +131 -0
- package/cordis.patch.yml +17 -0
- package/package.json +33 -0
- package/skills/dknowc-official-doc-writer/README.md +156 -0
- package/skills/dknowc-official-doc-writer/SKILL.md +462 -0
- package/skills/dknowc-official-doc-writer/config/format.json +101 -0
- package/skills/dknowc-official-doc-writer/config/user_profile.json.example +6 -0
- package/skills/dknowc-official-doc-writer/official-docs/input/mcp_intro_content.md +61 -0
- package/skills/dknowc-official-doc-writer/reference/anti_ai_patterns.md +113 -0
- package/skills/dknowc-official-doc-writer/reference/fact_discipline.md +62 -0
- package/skills/dknowc-official-doc-writer/reference/material_usage_guidance.md +138 -0
- package/skills/dknowc-official-doc-writer/reference/output_guide.md +288 -0
- package/skills/dknowc-official-doc-writer/reference/review_checklist.md +156 -0
- package/skills/dknowc-official-doc-writer/reference/search_guide.md +317 -0
- package/skills/dknowc-official-doc-writer/reference/search_intro.md +15 -0
- package/skills/dknowc-official-doc-writer/reference/search_policy.md +284 -0
- package/skills/dknowc-official-doc-writer/reference/standards/00_index.md +151 -0
- package/skills/dknowc-official-doc-writer/reference/standards/01_report.md +51 -0
- package/skills/dknowc-official-doc-writer/reference/standards/02_qingshi.md +53 -0
- package/skills/dknowc-official-doc-writer/reference/standards/03_pifu.md +48 -0
- package/skills/dknowc-official-doc-writer/reference/standards/04_tongzhi.md +51 -0
- package/skills/dknowc-official-doc-writer/reference/standards/05_yijian.md +55 -0
- package/skills/dknowc-official-doc-writer/reference/standards/06_han.md +81 -0
- package/skills/dknowc-official-doc-writer/reference/standards/07_minutes.md +46 -0
- package/skills/dknowc-official-doc-writer/reference/standards/08_tongbao.md +53 -0
- package/skills/dknowc-official-doc-writer/reference/standards/09_tonggao.md +45 -0
- package/skills/dknowc-official-doc-writer/reference/standards/10_gonggao.md +44 -0
- package/skills/dknowc-official-doc-writer/reference/standards/11_fuhan_approve.md +46 -0
- package/skills/dknowc-official-doc-writer/reference/standards/12_fuhan_objection.md +46 -0
- package/skills/dknowc-official-doc-writer/reference/standards/13_reminder.md +46 -0
- package/skills/dknowc-official-doc-writer/reference/standards/14_generic.md +41 -0
- package/skills/dknowc-official-doc-writer/reference/standards/15_business_docs.md +47 -0
- package/skills/dknowc-official-doc-writer/reference/standards/16_decision.md +47 -0
- package/skills/dknowc-official-doc-writer/reference/standards/17_resolution.md +45 -0
- package/skills/dknowc-official-doc-writer/reference/standards/18_order.md +44 -0
- package/skills/dknowc-official-doc-writer/reference/standards/19_gazette.md +45 -0
- package/skills/dknowc-official-doc-writer/reference/standards/20_motion.md +45 -0
- package/skills/dknowc-official-doc-writer/reference/standards/21_explanation.md +40 -0
- package/skills/dknowc-official-doc-writer/reference/standards/22_application.md +47 -0
- package/skills/dknowc-official-doc-writer/reference/standards/23_publicity.md +46 -0
- package/skills/dknowc-official-doc-writer/reference/standards/24_procurement.md +40 -0
- package/skills/dknowc-official-doc-writer/reference/standards/25_plan.md +42 -0
- package/skills/dknowc-official-doc-writer/reference/standards/26_summary.md +42 -0
- package/skills/dknowc-official-doc-writer/reference/standards/27_speech.md +43 -0
- package/skills/dknowc-official-doc-writer/reference/standards/28_rules.md +40 -0
- package/skills/dknowc-official-doc-writer/reference/standards/29_research.md +42 -0
- package/skills/dknowc-official-doc-writer/reference/standards/30_feasibility.md +42 -0
- package/skills/dknowc-official-doc-writer/reference/standards/31_review_material.md +40 -0
- package/skills/dknowc-official-doc-writer/reference/standards/32_ai_compute.md +41 -0
- package/skills/dknowc-official-doc-writer/reference/standards/99_expressions.md +569 -0
- package/skills/dknowc-official-doc-writer/reference/task_router.md +119 -0
- package/skills/dknowc-official-doc-writer/scripts/adapt_mcp_result.py +241 -0
- package/skills/dknowc-official-doc-writer/scripts/check_release.py +78 -0
- package/skills/dknowc-official-doc-writer/scripts/dkag_search.py +575 -0
- package/skills/dknowc-official-doc-writer/scripts/format_document.py +1756 -0
- package/skills/dknowc-official-doc-writer/scripts/initialize.py +178 -0
- package/skills/dknowc-official-doc-writer/scripts/mcp_direct.py +158 -0
- package/skills/dknowc-official-doc-writer/scripts/merge_search_results.py +223 -0
- package/skills/dknowc-official-doc-writer/scripts/outline_reference.py +202 -0
- package/skills/dknowc-official-doc-writer/scripts/prose_lint.py +242 -0
- package/skills/dknowc-official-doc-writer/scripts/register.mjs +218 -0
- package/skills/dknowc-official-doc-writer/scripts/render_trace_html.py +966 -0
- package/skills/dknowc-official-doc-writer/scripts/review_document.py +127 -0
- package/skills/dknowc-official-doc-writer/scripts/source_note_html.py +180 -0
- package/skills/dknowc-official-doc-writer/scripts/template_generator.py +975 -0
- package/skills/dknowc-trusted-consulting/README.md +63 -0
- package/skills/dknowc-trusted-consulting/SKILL.md +172 -0
- package/skills/dknowc-trusted-consulting/scripts/adapt_mcp_result.py +241 -0
- package/skills/dknowc-trusted-consulting/scripts/check_release.py +66 -0
- package/skills/dknowc-trusted-consulting/scripts/gov_chat.py +475 -0
- package/skills/dknowc-trusted-consulting/scripts/initialize.py +89 -0
- package/skills/dknowc-trusted-consulting/scripts/mcp_direct.py +158 -0
- package/skills/dknowc-trusted-consulting/scripts/register_key.mjs +181 -0
- package/skills/dknowc-trusted-consulting/scripts/render_trace_html.py +990 -0
- package/skills/dknowc-trusted-search/README.md +63 -0
- package/skills/dknowc-trusted-search/SKILL.md +232 -0
- package/skills/dknowc-trusted-search/official-docs/output/.gitkeep +0 -0
- package/skills/dknowc-trusted-search/official-docs/search-results/.gitkeep +0 -0
- package/skills/dknowc-trusted-search/scripts/adapt_mcp_result.py +241 -0
- package/skills/dknowc-trusted-search/scripts/check_release.py +79 -0
- package/skills/dknowc-trusted-search/scripts/deep_query.py +266 -0
- package/skills/dknowc-trusted-search/scripts/initialize.py +89 -0
- package/skills/dknowc-trusted-search/scripts/mcp_direct.py +158 -0
- package/skills/dknowc-trusted-search/scripts/register_key.mjs +181 -0
- package/skills/dknowc-trusted-search/scripts/render_policy_visualization.py +889 -0
- package/skills/dknowc-trusted-search/scripts/render_trace_html.py +1011 -0
- package/skills/dknowc-trusted-search/scripts/trusted_search.py +325 -0
- package/src/index.js +103 -0
|
@@ -0,0 +1,475 @@
|
|
|
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 指向会话工作区,未设置时回退到 skill 目录(SkillHub 兼容)
|
|
23
|
+
import os as _os
|
|
24
|
+
WS_ROOT = Path(_os.environ.get("DKNWOC_WS_ROOT") or _os.getcwd()).resolve()
|
|
25
|
+
|
|
26
|
+
SEARCH_RESULTS_DIR = WS_ROOT / "official-docs" / "search-results"
|
|
27
|
+
DEFAULTS = {
|
|
28
|
+
"area": "",
|
|
29
|
+
"session_id": "",
|
|
30
|
+
"request_id": "",
|
|
31
|
+
"interpretation_model": "autoModel",
|
|
32
|
+
"safe_answer_type": "active",
|
|
33
|
+
"safe_answer_scope": "all",
|
|
34
|
+
"credible_chat_scope": "all",
|
|
35
|
+
"search_mechanism": "autoSearch",
|
|
36
|
+
"material": True,
|
|
37
|
+
"recommended_questions": False,
|
|
38
|
+
"item": True,
|
|
39
|
+
"policy": True,
|
|
40
|
+
"traceurl": False,
|
|
41
|
+
"stream": True,
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def resolve_output_json(output_path: str) -> Path:
|
|
46
|
+
"""把咨询结果 JSON 落到本 Skill 的 official-docs/search-results/ 工作区。
|
|
47
|
+
|
|
48
|
+
裸文件名进 search-results/;带子路径的相对路径按 SKILL_ROOT 解析,
|
|
49
|
+
因此 official-docs/search-results/xxx.json 这类写法也可直接使用。
|
|
50
|
+
"""
|
|
51
|
+
raw = Path(output_path).expanduser()
|
|
52
|
+
if raw.is_absolute():
|
|
53
|
+
resolved = raw.resolve()
|
|
54
|
+
elif raw.parent == Path("."):
|
|
55
|
+
resolved = (SEARCH_RESULTS_DIR / raw.name).resolve()
|
|
56
|
+
else:
|
|
57
|
+
resolved = (WS_ROOT / raw).resolve()
|
|
58
|
+
if resolved.suffix.lower() != ".json":
|
|
59
|
+
resolved = resolved.with_suffix(".json")
|
|
60
|
+
return resolved
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _as_bool(value: Optional[str], default: bool = False) -> bool:
|
|
64
|
+
if value is None:
|
|
65
|
+
return default
|
|
66
|
+
value = value.strip()
|
|
67
|
+
if not value:
|
|
68
|
+
return default
|
|
69
|
+
return value.lower() in {"1", "true", "yes", "y", "on"}
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _pick(*values: Optional[str]) -> str:
|
|
73
|
+
for value in values:
|
|
74
|
+
if value:
|
|
75
|
+
return value.strip()
|
|
76
|
+
return ""
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _build_payload(args: argparse.Namespace) -> Dict[str, Any]:
|
|
80
|
+
material = args.material or bool(DEFAULTS["material"])
|
|
81
|
+
if args.no_material:
|
|
82
|
+
material = False
|
|
83
|
+
payload: Dict[str, Any] = {
|
|
84
|
+
"input": args.input,
|
|
85
|
+
"safeAnswerType": args.safe_answer_type or str(DEFAULTS["safe_answer_type"]),
|
|
86
|
+
"safeAnswerScope": args.safe_answer_scope or str(DEFAULTS["safe_answer_scope"]),
|
|
87
|
+
"knowledgeServiceType": "credibleChat",
|
|
88
|
+
"credibleChatScope": args.credible_chat_scope or str(DEFAULTS["credible_chat_scope"]),
|
|
89
|
+
"searchMechanism": args.search_mechanism or str(DEFAULTS["search_mechanism"]),
|
|
90
|
+
"interpretationModel": args.interpretation_model or str(DEFAULTS["interpretation_model"]),
|
|
91
|
+
"material": material,
|
|
92
|
+
"recommendedQuestions": args.recommended_questions or bool(DEFAULTS["recommended_questions"]),
|
|
93
|
+
"item": False if args.no_item else args.item or bool(DEFAULTS["item"]),
|
|
94
|
+
"policy": False if args.no_policy else args.policy or bool(DEFAULTS["policy"]),
|
|
95
|
+
"traceurl": args.traceurl or bool(DEFAULTS["traceurl"]),
|
|
96
|
+
"stream": args.stream or (not args.no_stream and bool(DEFAULTS["stream"])),
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
if args.show_reasoning:
|
|
100
|
+
payload["interpretationModel"] = "deepModel"
|
|
101
|
+
|
|
102
|
+
request_id = args.request_id or str(DEFAULTS["request_id"])
|
|
103
|
+
if args.auto_request_id and not request_id:
|
|
104
|
+
request_id = uuid.uuid4().hex + uuid.uuid4().hex[:8]
|
|
105
|
+
|
|
106
|
+
optional = {
|
|
107
|
+
"area": args.area or str(DEFAULTS["area"]),
|
|
108
|
+
"requestId": request_id,
|
|
109
|
+
"sessionId": args.session_id or str(DEFAULTS["session_id"]),
|
|
110
|
+
}
|
|
111
|
+
for key, value in optional.items():
|
|
112
|
+
if value:
|
|
113
|
+
payload[key] = value
|
|
114
|
+
|
|
115
|
+
return payload
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _read_sse_response(resp: Any) -> str:
|
|
119
|
+
chunks = []
|
|
120
|
+
while True:
|
|
121
|
+
raw_line = resp.readline()
|
|
122
|
+
if not raw_line:
|
|
123
|
+
break
|
|
124
|
+
line = raw_line.decode("utf-8", errors="replace")
|
|
125
|
+
chunks.append(line)
|
|
126
|
+
if line.strip() in {"data: [DONE]", "[DONE]"}:
|
|
127
|
+
break
|
|
128
|
+
return "".join(chunks).replace("\x00", "")
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _post(url: str, api_key: str, payload: Dict[str, Any], timeout: int) -> str:
|
|
132
|
+
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
|
133
|
+
req = urllib.request.Request(url, data=data, method="POST")
|
|
134
|
+
req.add_header("api-key", api_key)
|
|
135
|
+
req.add_header("Content-Type", "application/json")
|
|
136
|
+
|
|
137
|
+
try:
|
|
138
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
139
|
+
if payload.get("stream"):
|
|
140
|
+
return _read_sse_response(resp)
|
|
141
|
+
return resp.read().decode("utf-8", errors="replace").replace("\x00", "")
|
|
142
|
+
except urllib.error.HTTPError as e:
|
|
143
|
+
detail = e.read().decode("utf-8", errors="ignore")
|
|
144
|
+
print(f"错误:HTTP {e.code} {detail or e.reason}", file=sys.stderr)
|
|
145
|
+
sys.exit(1)
|
|
146
|
+
except urllib.error.URLError as e:
|
|
147
|
+
print(f"错误:网络请求失败 - {e.reason}", file=sys.stderr)
|
|
148
|
+
sys.exit(1)
|
|
149
|
+
except socket.timeout:
|
|
150
|
+
print("错误:接口流式响应读取超时。请确认接口是否持续输出 SSE 数据,或适当增大 --timeout。", file=sys.stderr)
|
|
151
|
+
sys.exit(1)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
class _StreamingCleaner:
|
|
155
|
+
def __init__(self) -> None:
|
|
156
|
+
self._buffer = ""
|
|
157
|
+
self._hold_chars = 512
|
|
158
|
+
|
|
159
|
+
def feed(self, text: str) -> str:
|
|
160
|
+
self._buffer += text
|
|
161
|
+
if len(self._buffer) <= self._hold_chars:
|
|
162
|
+
return ""
|
|
163
|
+
cut = len(self._buffer) - self._hold_chars
|
|
164
|
+
|
|
165
|
+
last_tag_start = self._buffer.rfind("<", 0, cut)
|
|
166
|
+
if last_tag_start != -1:
|
|
167
|
+
next_tag_end = self._buffer.find(">", last_tag_start)
|
|
168
|
+
if next_tag_end == -1 or next_tag_end >= cut:
|
|
169
|
+
cut = last_tag_start
|
|
170
|
+
|
|
171
|
+
last_citation_start = max(
|
|
172
|
+
self._buffer.rfind("[^", 0, cut),
|
|
173
|
+
self._buffer.rfind("[", 0, cut),
|
|
174
|
+
)
|
|
175
|
+
if last_citation_start != -1:
|
|
176
|
+
next_citation_end = self._buffer.find("]", last_citation_start)
|
|
177
|
+
if next_citation_end == -1 or next_citation_end >= cut:
|
|
178
|
+
cut = last_citation_start
|
|
179
|
+
|
|
180
|
+
safe, self._buffer = self._buffer[:cut], self._buffer[cut:]
|
|
181
|
+
return _format_answer_content(safe)
|
|
182
|
+
|
|
183
|
+
def finish(self) -> str:
|
|
184
|
+
text = _format_answer_content(self._buffer)
|
|
185
|
+
self._buffer = ""
|
|
186
|
+
return text
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _post_streaming_to_stdout(url: str, api_key: str, payload: Dict[str, Any], timeout: int) -> None:
|
|
190
|
+
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
|
191
|
+
req = urllib.request.Request(url, data=data, method="POST")
|
|
192
|
+
req.add_header("api-key", api_key)
|
|
193
|
+
req.add_header("Content-Type", "application/json")
|
|
194
|
+
|
|
195
|
+
cleaner = _StreamingCleaner()
|
|
196
|
+
trace_url = ""
|
|
197
|
+
wrote_content = False
|
|
198
|
+
|
|
199
|
+
try:
|
|
200
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
201
|
+
while True:
|
|
202
|
+
raw_line = resp.readline()
|
|
203
|
+
if not raw_line:
|
|
204
|
+
break
|
|
205
|
+
line = raw_line.decode("utf-8", errors="replace").replace("\x00", "").strip()
|
|
206
|
+
if not line.startswith("data:"):
|
|
207
|
+
continue
|
|
208
|
+
chunk = line[5:].strip()
|
|
209
|
+
if chunk == "[DONE]":
|
|
210
|
+
break
|
|
211
|
+
try:
|
|
212
|
+
obj = json.loads(chunk)
|
|
213
|
+
except json.JSONDecodeError:
|
|
214
|
+
continue
|
|
215
|
+
|
|
216
|
+
if isinstance(obj.get("traceUrl"), str):
|
|
217
|
+
trace_url = obj["traceUrl"].strip()
|
|
218
|
+
|
|
219
|
+
piece = _extract_piece(obj)
|
|
220
|
+
if not piece:
|
|
221
|
+
continue
|
|
222
|
+
|
|
223
|
+
cleaned = cleaner.feed(piece)
|
|
224
|
+
if cleaned:
|
|
225
|
+
print(cleaned, end="", flush=True)
|
|
226
|
+
wrote_content = True
|
|
227
|
+
|
|
228
|
+
tail = cleaner.finish()
|
|
229
|
+
if tail:
|
|
230
|
+
print(tail, end="", flush=True)
|
|
231
|
+
wrote_content = True
|
|
232
|
+
if wrote_content:
|
|
233
|
+
print()
|
|
234
|
+
if trace_url:
|
|
235
|
+
print("\n可信溯源报告")
|
|
236
|
+
print(trace_url)
|
|
237
|
+
except urllib.error.HTTPError as e:
|
|
238
|
+
detail = e.read().decode("utf-8", errors="ignore")
|
|
239
|
+
print(f"错误:HTTP {e.code} {detail or e.reason}", file=sys.stderr)
|
|
240
|
+
sys.exit(1)
|
|
241
|
+
except urllib.error.URLError as e:
|
|
242
|
+
print(f"错误:网络请求失败 - {e.reason}", file=sys.stderr)
|
|
243
|
+
sys.exit(1)
|
|
244
|
+
except socket.timeout:
|
|
245
|
+
print("错误:接口流式响应读取超时。请确认接口是否持续输出 SSE 数据,或适当增大 --timeout。", file=sys.stderr)
|
|
246
|
+
sys.exit(1)
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _iter_sse_payloads(text: str) -> Iterable[Dict[str, Any]]:
|
|
250
|
+
for raw_line in text.splitlines():
|
|
251
|
+
line = raw_line.strip()
|
|
252
|
+
if not line.startswith("data:"):
|
|
253
|
+
continue
|
|
254
|
+
chunk = line[5:].strip()
|
|
255
|
+
if chunk == "[DONE]":
|
|
256
|
+
break
|
|
257
|
+
try:
|
|
258
|
+
yield json.loads(chunk)
|
|
259
|
+
except json.JSONDecodeError:
|
|
260
|
+
continue
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def _merge_sse_result(text: str) -> Dict[str, Any]:
|
|
264
|
+
result: Dict[str, Any] = {}
|
|
265
|
+
resp: Dict[str, Any] = {}
|
|
266
|
+
content_parts = []
|
|
267
|
+
reasoning_parts = []
|
|
268
|
+
|
|
269
|
+
for obj in _iter_sse_payloads(text):
|
|
270
|
+
for key in ("requestId", "sessionId", "safeType", "knowledgeScope", "created", "area", "traceUrl"):
|
|
271
|
+
if key in obj and key not in result:
|
|
272
|
+
result[key] = obj[key]
|
|
273
|
+
|
|
274
|
+
for key in ("referenceMaterials", "recommendationItems", "policyFiles"):
|
|
275
|
+
if key in obj and key not in result:
|
|
276
|
+
result[key] = obj[key]
|
|
277
|
+
|
|
278
|
+
chunk_resp = obj.get("resp")
|
|
279
|
+
if isinstance(chunk_resp, dict):
|
|
280
|
+
for key in ("waitText", "areaTip"):
|
|
281
|
+
if key in chunk_resp and key not in resp:
|
|
282
|
+
resp[key] = chunk_resp[key]
|
|
283
|
+
content = chunk_resp.get("content")
|
|
284
|
+
if isinstance(content, str):
|
|
285
|
+
content_parts.append(content)
|
|
286
|
+
reasoning = chunk_resp.get("reasoning_content")
|
|
287
|
+
if isinstance(reasoning, str):
|
|
288
|
+
reasoning_parts.append(reasoning)
|
|
289
|
+
|
|
290
|
+
choices = obj.get("choices")
|
|
291
|
+
if isinstance(choices, list) and choices:
|
|
292
|
+
delta = choices[0].get("delta", {})
|
|
293
|
+
if isinstance(delta, dict):
|
|
294
|
+
for key in ("waitText", "areaTip"):
|
|
295
|
+
if key in delta and key not in resp:
|
|
296
|
+
resp[key] = delta[key]
|
|
297
|
+
content = delta.get("content")
|
|
298
|
+
if isinstance(content, str):
|
|
299
|
+
content_parts.append(content)
|
|
300
|
+
reasoning = delta.get("reasoning_content")
|
|
301
|
+
if isinstance(reasoning, str):
|
|
302
|
+
reasoning_parts.append(reasoning)
|
|
303
|
+
|
|
304
|
+
if content_parts:
|
|
305
|
+
resp["content"] = "".join(content_parts)
|
|
306
|
+
if reasoning_parts:
|
|
307
|
+
resp["reasoning_content"] = "".join(reasoning_parts)
|
|
308
|
+
if resp:
|
|
309
|
+
result["resp"] = resp
|
|
310
|
+
return result
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def _normalize_result(text: str) -> Dict[str, Any]:
|
|
314
|
+
stripped = text.strip()
|
|
315
|
+
if not stripped:
|
|
316
|
+
return {"resp": {"content": ""}}
|
|
317
|
+
if "data:" in stripped:
|
|
318
|
+
return _merge_sse_result(stripped)
|
|
319
|
+
try:
|
|
320
|
+
body = json.loads(stripped)
|
|
321
|
+
except json.JSONDecodeError:
|
|
322
|
+
return {"resp": {"content": stripped}}
|
|
323
|
+
if isinstance(body, dict):
|
|
324
|
+
return body
|
|
325
|
+
return {"resp": {"content": body}}
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def _strip_html(text: str) -> str:
|
|
329
|
+
return re.sub(r"<[^>]+>", "", text)
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def _format_answer_content(text: str) -> str:
|
|
333
|
+
cleaned = _strip_html(text)
|
|
334
|
+
return re.sub(r"\[\^?\d+\^?\]", "", cleaned)
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def _print_trace_report(result: Dict[str, Any]) -> None:
|
|
338
|
+
trace_url = result.get("traceUrl")
|
|
339
|
+
if isinstance(trace_url, str) and trace_url.strip():
|
|
340
|
+
print("\n可信溯源报告")
|
|
341
|
+
print(trace_url.strip())
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def _print_summary(result: Dict[str, Any], show_reasoning: bool) -> None:
|
|
345
|
+
resp = result.get("resp", {})
|
|
346
|
+
if isinstance(resp, dict):
|
|
347
|
+
if resp.get("waitText"):
|
|
348
|
+
print(resp["waitText"])
|
|
349
|
+
if resp.get("areaTip"):
|
|
350
|
+
print(resp["areaTip"])
|
|
351
|
+
|
|
352
|
+
content = resp.get("content")
|
|
353
|
+
if content:
|
|
354
|
+
print(_format_answer_content(content))
|
|
355
|
+
|
|
356
|
+
reasoning = resp.get("reasoning_content")
|
|
357
|
+
if show_reasoning and reasoning:
|
|
358
|
+
print(f"\n模型思考过程:\n{reasoning}")
|
|
359
|
+
elif resp:
|
|
360
|
+
print(resp)
|
|
361
|
+
|
|
362
|
+
_print_trace_report(result)
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def _print_result(text: str, raw: bool, json_only: bool, show_reasoning: bool, output: Optional[str] = None) -> None:
|
|
366
|
+
result = _normalize_result(text)
|
|
367
|
+
|
|
368
|
+
if json_only:
|
|
369
|
+
payload = {"success": True, "data": result}
|
|
370
|
+
if output:
|
|
371
|
+
output_path = resolve_output_json(output)
|
|
372
|
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
373
|
+
output_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
374
|
+
print(f"已保存咨询结果 JSON:{_rel_to_ws(output_path)}")
|
|
375
|
+
return
|
|
376
|
+
print(json.dumps(payload, ensure_ascii=False, indent=2))
|
|
377
|
+
return
|
|
378
|
+
|
|
379
|
+
_print_summary(result, show_reasoning)
|
|
380
|
+
if raw:
|
|
381
|
+
print("\n=== RAW_RESPONSE_START ===")
|
|
382
|
+
print(text.strip())
|
|
383
|
+
print("=== RAW_RESPONSE_END ===")
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def _extract_piece(obj: Dict[str, Any]) -> str:
|
|
387
|
+
choices = obj.get("choices")
|
|
388
|
+
if isinstance(choices, list) and choices:
|
|
389
|
+
delta = choices[0].get("delta", {})
|
|
390
|
+
if isinstance(delta, dict):
|
|
391
|
+
for key in ("content", "reasoning_content", "areaTip", "waitText"):
|
|
392
|
+
value = delta.get(key)
|
|
393
|
+
if isinstance(value, str):
|
|
394
|
+
return value
|
|
395
|
+
|
|
396
|
+
resp = obj.get("resp")
|
|
397
|
+
if isinstance(resp, dict):
|
|
398
|
+
content = resp.get("content")
|
|
399
|
+
if isinstance(content, str):
|
|
400
|
+
return content
|
|
401
|
+
|
|
402
|
+
content = obj.get("content")
|
|
403
|
+
if isinstance(content, str):
|
|
404
|
+
return content
|
|
405
|
+
return ""
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def main() -> None:
|
|
409
|
+
parser = argparse.ArgumentParser(description="深知可信咨询 credibleChat 调用脚本")
|
|
410
|
+
parser.add_argument("input", help="用户政务问题")
|
|
411
|
+
parser.add_argument("--endpoint", help="覆盖接口地址")
|
|
412
|
+
parser.add_argument("--area", help="覆盖地域")
|
|
413
|
+
parser.add_argument("--session-id", help="覆盖 sessionId")
|
|
414
|
+
parser.add_argument("--request-id", help="覆盖 requestId")
|
|
415
|
+
parser.add_argument("--auto-request-id", action="store_true", help="未传 requestId 时自动生成")
|
|
416
|
+
parser.add_argument("--safe-answer-scope", choices=["none", "all", "risk"], help="覆盖安全代答范围")
|
|
417
|
+
parser.add_argument("--safe-answer-type", choices=["active", "conservative"], help="覆盖安全代答模式")
|
|
418
|
+
parser.add_argument("--credible-chat-scope", choices=["onlyNorms", "needNorms", "all"], help="覆盖可信问答范围")
|
|
419
|
+
parser.add_argument("--search-mechanism", choices=["quickSearch", "autoSearch", "deepSearch"], help="覆盖搜索机制")
|
|
420
|
+
parser.add_argument("--interpretation-model", choices=["autoModel", "fastModel", "deepModel"], help="覆盖解读模型")
|
|
421
|
+
parser.add_argument("--material", action="store_true", help="返回参考材料")
|
|
422
|
+
parser.add_argument("--no-material", action="store_true", help="不返回参考材料")
|
|
423
|
+
parser.add_argument("--recommended-questions", action="store_true", help="返回推荐问题")
|
|
424
|
+
parser.add_argument("--item", action="store_true", help="返回办理事项")
|
|
425
|
+
parser.add_argument("--no-item", action="store_true", help="不返回办理事项")
|
|
426
|
+
parser.add_argument("--policy", action="store_true", help="返回政策文件")
|
|
427
|
+
parser.add_argument("--no-policy", action="store_true", help="不返回政策文件")
|
|
428
|
+
parser.add_argument("--traceurl", action="store_true", help="返回可信溯源报告链接")
|
|
429
|
+
parser.add_argument("--stream", action="store_true", help="开启流式返回")
|
|
430
|
+
parser.add_argument("--no-stream", action="store_true", help="关闭流式")
|
|
431
|
+
parser.add_argument("--show-payload", action="store_true", help="打印请求参数")
|
|
432
|
+
parser.add_argument("--dry-run", action="store_true", help="只打印请求参数,不发起请求")
|
|
433
|
+
parser.add_argument("--raw", action="store_true", help="打印原始响应")
|
|
434
|
+
parser.add_argument("--json-only", action="store_true", help="仅输出聚合后的 JSON")
|
|
435
|
+
parser.add_argument("--output", "-o", help="咨询结果 JSON 文件名,写入 official-docs/search-results/(配合 --json-only 使用)")
|
|
436
|
+
parser.add_argument("--show-reasoning", action="store_true", help="显示 deepModel 思考过程,并自动使用 deepModel")
|
|
437
|
+
parser.add_argument("--timeout", type=int, default=90, help="请求超时秒数")
|
|
438
|
+
args = parser.parse_args()
|
|
439
|
+
|
|
440
|
+
endpoint = _pick(
|
|
441
|
+
args.endpoint,
|
|
442
|
+
os.environ.get("DKNOWC_KNOW_ENDPOINT"),
|
|
443
|
+
os.environ.get("DKNOWC_GOV_ZHICHA_ENDPOINT"),
|
|
444
|
+
DEFAULT_ENDPOINT,
|
|
445
|
+
)
|
|
446
|
+
api_key = _pick(
|
|
447
|
+
os.environ.get("DKNOWC_API_KEY"),
|
|
448
|
+
)
|
|
449
|
+
|
|
450
|
+
if not endpoint:
|
|
451
|
+
print("错误:缺少 endpoint,请通过脚本默认值、--endpoint 或环境变量配置。", file=sys.stderr)
|
|
452
|
+
sys.exit(2)
|
|
453
|
+
if not api_key:
|
|
454
|
+
print("错误:缺少 api_key,请配置环境变量 DKNOWC_API_KEY。", file=sys.stderr)
|
|
455
|
+
sys.exit(2)
|
|
456
|
+
|
|
457
|
+
payload = _build_payload(args)
|
|
458
|
+
if args.show_payload:
|
|
459
|
+
safe_payload = dict(payload)
|
|
460
|
+
print("=== 请求参数 ===")
|
|
461
|
+
print(json.dumps(safe_payload, ensure_ascii=False, indent=2))
|
|
462
|
+
print()
|
|
463
|
+
if args.dry_run:
|
|
464
|
+
return
|
|
465
|
+
|
|
466
|
+
if payload.get("stream") and not (args.raw or args.json_only or args.show_reasoning):
|
|
467
|
+
_post_streaming_to_stdout(endpoint, api_key, payload, args.timeout)
|
|
468
|
+
return
|
|
469
|
+
|
|
470
|
+
text = _post(endpoint, api_key, payload, args.timeout)
|
|
471
|
+
_print_result(text, args.raw, args.json_only, args.show_reasoning, args.output)
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
if __name__ == "__main__":
|
|
475
|
+
main()
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""深知可信咨询 SkillHub public 版初始化检查。
|
|
3
|
+
|
|
4
|
+
Public 版统一只从环境变量 DKNOWC_API_KEY 读取 API Key,不读取、不写入本地 config.ini 中的 Key。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
API_KEY_ENV = "DKNOWC_API_KEY"
|
|
12
|
+
PLACEHOLDER_KEYS = {"", "your_api_key_here", "你的深知可信统一接口 API Key", "你的深知可信咨询 API Key"}
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _looks_like_key(value: str) -> bool:
|
|
16
|
+
value = (value or "").strip()
|
|
17
|
+
return value not in PLACEHOLDER_KEYS
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _in_dsh() -> bool:
|
|
21
|
+
"""dsh 环境标志:dsh 的 bash 工具会注入 DSH_SHELL=1。
|
|
22
|
+
|
|
23
|
+
dsh 场景下,脚本子进程无法隐式继承 DKNOWC_API_KEY(dsh 安全机制会清理
|
|
24
|
+
名字含 KEY 的环境变量),但 dsh 插件会通过 shell-env 显式通道把该 Key
|
|
25
|
+
注入为 DSH_DKNOWC_API_KEY。因此检查 DSH_DKNOWC_API_KEY 即可真实判断
|
|
26
|
+
"dsh 主进程环境变量是否已配置 DKNOWC_API_KEY"。
|
|
27
|
+
"""
|
|
28
|
+
return os.environ.get("DSH_SHELL") == "1"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def check_api_key_config():
|
|
32
|
+
if _in_dsh():
|
|
33
|
+
# dsh 场景:读取插件注入的 DSH_DKNOWC_API_KEY(来源为 dsh 主进程的 DKNOWC_API_KEY)
|
|
34
|
+
api_key = os.environ.get("DSH_DKNOWC_API_KEY", "").strip()
|
|
35
|
+
if _looks_like_key(api_key):
|
|
36
|
+
return {
|
|
37
|
+
"api_key_configured": True,
|
|
38
|
+
"api_key_env": "DKNOWC_API_KEY (DSH_DKNOWC_API_KEY)",
|
|
39
|
+
"api_key_source": "environment",
|
|
40
|
+
"api_key_hint": None,
|
|
41
|
+
"search_ready": True,
|
|
42
|
+
"search_note": "dsh 场景:接口经深知可信工作台 MCP 转接(credible_chat),API Key 由 dsh 主进程环境变量 DKNOWC_API_KEY 提供(经 shell-env 显式注入为 DSH_DKNOWC_API_KEY)。",
|
|
43
|
+
}
|
|
44
|
+
return {
|
|
45
|
+
"api_key_configured": False,
|
|
46
|
+
"api_key_env": API_KEY_ENV,
|
|
47
|
+
"api_key_source": None,
|
|
48
|
+
"api_key_hint": f"未检测到可用的 {API_KEY_ENV}(dsh 主进程环境变量未配置或为空)。需要先将有效的 API Key 配置到启动 dsh 的环境变量 {API_KEY_ENV}(如 ~/.zshrc),再重启 dsh 或新建会话。",
|
|
49
|
+
"search_ready": False,
|
|
50
|
+
"search_note": f"当前缺少 {API_KEY_ENV},暂时无法获取深知可信内容。",
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
api_key = os.environ.get(API_KEY_ENV, "").strip()
|
|
54
|
+
if _looks_like_key(api_key):
|
|
55
|
+
return {
|
|
56
|
+
"api_key_configured": True,
|
|
57
|
+
"api_key_env": API_KEY_ENV,
|
|
58
|
+
"api_key_source": "environment",
|
|
59
|
+
"api_key_hint": None,
|
|
60
|
+
"search_ready": True,
|
|
61
|
+
"search_note": None,
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
return {
|
|
65
|
+
"api_key_configured": False,
|
|
66
|
+
"api_key_env": API_KEY_ENV,
|
|
67
|
+
"api_key_source": None,
|
|
68
|
+
"api_key_hint": f"本 Skill 需要通过环境变量 {API_KEY_ENV} 调用深知可信统一接口获取可信内容,当前还未配置。请先注册或登录深知可信智能 MaaS 账号获取 API Key,再注入该环境变量。",
|
|
69
|
+
"search_ready": False,
|
|
70
|
+
"search_note": f"当前未检测到可用的 {API_KEY_ENV},暂时无法获取深知可信内容。",
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def main():
|
|
75
|
+
status = check_api_key_config()
|
|
76
|
+
blocking_issues = []
|
|
77
|
+
if not status["api_key_configured"]:
|
|
78
|
+
blocking_issues.append("api_key_missing")
|
|
79
|
+
|
|
80
|
+
print(json.dumps({
|
|
81
|
+
**status,
|
|
82
|
+
"blocking_issues": blocking_issues,
|
|
83
|
+
"ready": not blocking_issues,
|
|
84
|
+
"maas_platform_url": "https://platform.dknowc.cn/",
|
|
85
|
+
}, ensure_ascii=False, indent=2))
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
if __name__ == "__main__":
|
|
89
|
+
main()
|