为 Skills 定义输入与输出规范
写清格式、缺省、边界及交付时机,再用真实文档和结构化结果验证。
学完这一章,你能够
- 写清格式、缺省、边界及交付时机,再用真实文档和结构化结果验证。
明确输入的形式和默认值
先写清接受文件、文本、URL 还是参数,并校验对应结构。表格可要求 CSV 为 UTF-8,首行表头。Excel 应用工作簿读取器。文件路径可能必填,列名、输出形式和精度可以约定缺省行为。
在表格分析说明中可指定数值列、表格或文字摘要、精度两位及 50 MB 示例上限。把上限写成明确单位,给缺文件和不支持的格式提供恢复动作。本站本章文档程序明确限制 10 MiB,接受 TXT、DOCX 与 PDF。
用输出合同描述可核对的结果
统计报告可包含行数、均值、极值与空值,另记混合类型等质量问题。输出先说明基本信息,再给核心结果、主题关键词和生成文件位置。按用途决定对话 Markdown、可下载文件或供下一步消费的 JSON、CSV。
宿主可在读取后反馈大小、行列信息,耗时较久时给进度,完成再交付真实产物。十秒是示例阈值,实际应取任务的等待预算。托管环境可能有 /home/claude/ 临时区、/mnt/user-data/outputs/ 交付区与 present_files。使用时先确认宿主工具和授权的目录。
本站选择 stderr 作为进度通道,stdout 只出一个 JSON。默认不保存。显式 --output 写入新文件,下载前应打开或比对字节。
处理正文、文字层及缺项
同一任务可约定短、中、长三档,默认中档,保留原文语种并可指定重点。本站短档最多三段原句,中档最多五段原句合并为一段,长档最多分成三段。重点选项优先呈现含给定词的段落。此方法是可溯源摘录,生成式复述和翻译需要另一个经过验证的实现。
程序用 PDFium 提取 PDF 文字,保留页数。用 python-docx 读取 Word 段落和表格;Word 页数依版式而定,无法从此例得到时输出 null。纯文本按 UTF-8 解码。扫描图片分支提示 OCR,损坏、过大和缺失文件各有诊断。关键词最多八项,短输入可更少。
按 JSON 格式消费结果
成功带 data,失败带 error.code、message 和 action。脚本以实际退出码配合调用方。解析后再核对数据字段、内容来源及真实文件。不能把字符串长度误当字数,本站标明词边界估计。
输入的四个要素
| 条目 | 用途与条件 |
|---|---|
| 类型 | 选择可访问的文件、文本、URL 或参数。文件处理先进入对应读取器。 |
| 格式 | 验证后缀、编码和必要结构,读取后确认实际数据。 |
| 必填与可选 | 路径必填,长度和焦点由调用方选择。 |
| 缺省值 | 本例默认中档、原文语种、不落盘。 |
为不同读者选择输出
| 条目 | 用途与条件 |
|---|---|
| 对话内容 | 可用 Markdown 展示受控数据。 |
| 交付文件 | 文件真实存在后使用宿主支持的交付操作。 |
| 供下一步消费 | 用批准的本地目录交接 JSON 或 CSV,明确清理时机。 |
运行三种文档输入和 JSON 输出合同
"""Create a grounded, extractive recap of a local text, PDF or Word file."""
import argparse
from collections import Counter
from importlib import import_module
import io
import json
from pathlib import Path
import re
import sys
from zipfile import BadZipFile
FORMATS={".txt":"text",".pdf":"pdf",".docx":"docx"}
DEPENDENCIES={"pdf":("pypdfium2","pypdfium2"),"docx":("docx","python-docx")}
MAX_BYTES=10*1024*1024
STOP={"the","for","are","was","with","and","from","this","that","these"}
class ContractError(Exception):
def __init__(self,status,code,message,action,exit_code):
super().__init__(message)
self.status,self.code,self.action,self.exit_code=status,code,action,exit_code
def payload(self):
return dict(status=self.status,error={"code":self.code,"message":str(self),"action":self.action})
def extract(raw,kind):
if kind=="text":
return None,raw.decode("utf-8-sig")
module,package=DEPENDENCIES[kind]
try:
reader=import_module(module)
except ModuleNotFoundError as error:
if error.name!=module:
raise
raise ContractError("process_error","MISSING_DEPENDENCY",f"reader {package} is unavailable",
"run with the declared dependency in a separate environment",4) from error
if kind=="docx":
try:
doc=reader.Document(io.BytesIO(raw))
except (ValueError,BadZipFile,KeyError) as error:
raise ContractError("process_error","DAMAGED_DOCX","unable to read the Word package",
"open and repair or re-export the document",4) from error
blocks=[p.text for p in doc.paragraphs]
for table in doc.tables:
blocks.extend(" | ".join(cell.text for cell in row.cells) for row in table.rows)
return None,"\n".join(blocks)
try:
with reader.PdfDocument(raw) as pdf:
blocks=[]
for index in range(len(pdf)):
page=pdf[index]
try:
text=page.get_textpage()
try:
blocks.append(text.get_text_bounded())
finally:
text.close()
finally:
page.close()
return len(pdf),"\n".join(blocks)
except reader.PdfiumError as error:
raise ContractError("process_error","DAMAGED_PDF","unable to open the PDF reader",
"use a valid unlocked PDF or re-export it",4) from error
def recap(text,length,focus):
# Keep the original sentence text and its ordering when possible.
chunks=[line.strip() for line in re.split(r"(?<=[.!?。!?])\s+|[\r\n]+",text) if line.strip()]
if focus:
chunks=sorted(chunks,key=lambda item:focus.casefold() not in item.casefold())
take={"short":3,"medium":5,"long":9}[length]
selected=chunks[:take]
if length=="long":
return "\n\n".join(" ".join(selected[i:i+3]) for i in range(0,len(selected),3))
return " ".join(selected)
def summarize(path,length,focus,progress,limit):
if path is None:
raise ContractError("input_error","MISSING_INPUT","no input file was supplied","choose a local document",2)
kind=FORMATS.get(path.suffix.casefold())
if kind is None:
raise ContractError("input_error","FORMAT","expected .txt, .pdf or .docx","choose a supported file format",2)
with path.open("rb") as stream:
raw=stream.read(limit+1)
if not raw:
raise ContractError("input_error","EMPTY","input file is empty","choose a file containing text",2)
if len(raw)>limit:
raise ContractError("input_error","SIZE","input exceeds the byte limit","split the document before retry",2)
if progress:
print(f"read {len(raw)} bytes",file=sys.stderr,flush=True)
page_count,text=extract(raw,kind)
if not text.strip():
code="NO_TEXT_LAYER" if kind=="pdf" else "NO_TEXT"
action="use OCR for an image-only PDF" if kind=="pdf" else "supply a file with nonempty text"
raise ContractError("result_error",code,"no text was returned by the reader",action,5)
words=re.findall(r"\b[\w-]+\b",text)
counts=Counter(w.casefold() for w in words if len(w)>2 and w.casefold() not in STOP)
result=dict(title=next(line.strip() for line in text.splitlines() if line.strip()),
pages=page_count,word_count_estimate=len(words),length=length,method="extractive_local",
summary=recap(text,length,focus),keywords=[word for word,_ in counts.most_common(8)])
if not result["summary"]:
raise ContractError("result_error","EMPTY_SUMMARY","no extract could be produced","review the source text",5)
if progress:
print("summary ready",file=sys.stderr,flush=True)
return result
def main(argv=None):
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument("path",type=Path,nargs="?")
parser.add_argument("--length",choices=["short","medium","long"],default="medium")
parser.add_argument("--focus",default="")
parser.add_argument("--progress",action="store_true")
parser.add_argument("--max-bytes",type=int,default=MAX_BYTES)
parser.add_argument("--output",type=Path)
args=parser.parse_args(argv)
try:
if not 0<args.max_bytes<=MAX_BYTES:
raise ContractError("input_error","INVALID_LIMIT","byte limit must be within the supported range",
"choose a positive limit up to 10 MiB",2)
data=summarize(args.path,args.length,args.focus,args.progress,args.max_bytes)
result=dict(status="success",data=data)
if args.output:
with args.output.open("x",encoding="utf8") as target:
json.dump(result,target,ensure_ascii=False)
target.write("\n")
except ContractError as error:
result=error.payload()
code=error.exit_code
except FileNotFoundError:
result=ContractError("input_error","NOT_FOUND","input or output directory not found","check the specified location",2).payload()
code=2
except UnicodeDecodeError:
result=ContractError("process_error","ENCODING","input could not be decoded", "provide UTF-8 text or a new export",4).payload()
code=4
except (OSError,ModuleNotFoundError):
result=ContractError("process_error","READER_OR_IO","reader or file operation failed",
"check dependencies, use an authorized location and a new output name",4).payload()
code=4
else:
code=0
print(json.dumps(result,ensure_ascii=False))
return code
if __name__=="__main__":
raise SystemExit(main())
- 纯文本、带文字层的 PDF 和 DOCX 生成可定位的摘录和元数据。扫描页单列报错。默认输出给调用方,显式指定新路径才保存 JSON。
所需环境:Windows、Python 3.12。各实验所需工具和版本见下载包 README。
当前源码 SHA256:1deb1a1c40288455efcbf84e94824417408cc1831a3d869f5294e8d3d02ee28a
运行本地实验
解压后按 README 运行当前章节对应的脚本,并查看真实输出。
所需环境:Windows、Python 3.12。各实验所需工具和版本见下载包 README。
ZIP SHA256:333b271d3b5bf1eb1e5c6479e01fd2fd8aa2b441a6c2ad4deb005a2b6155819e
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
要检测是否生成了可下载报告,需要验证哪些条件?
展开参考解答
确认用户选择了保存,检查真实文件字节和输出路径,再用宿主提供的交付入口。