预解析取值抽取
预解析取值抽取
用正则找出候选的邮箱、电话号码和金额,再让 TypeSafe 选出问题所要的那一段,好让代码把原样的值归一化。
正则找出候选值,TypeSafe 挑出问题所要的那一个,代码原样复制。
这里的 find 和 pick 这对搭档,可以直接指向你自己的文档;三个完整的例子演示了它的用法:发件人希望把发票发去的地址、格式为 +14155550177 的电话号码,以及一条被标记为扣款的、金额为 1315.50 USD 的发票总额。
TypeSafe 只能在你交给它的选项里挑一个,所以候选必须先被找出来。整个过程分三步:正则找到候选,TypeSafe 挑一个,代码再复制挑中的结果:
- 用正则从文本里找出候选值。把正则调得宁可多找。
- TypeSafe 挑出问题问的是哪个候选,并读出代码下游需要的属性(货币、国家、一笔金额是贷记还是扣款)。
- 代码复制挑中的值并归一化。
因为 TypeSafe 只在正则找到的那些片段里做选择,你拿回的值必然是其中之一,原样未改。它不可能凭空编出一个值,也不会把数字的顺序调转。
正则在文档里找到候选值,TypeSafe 挑中一个,下游代码再把它归一化并据此行动。
准备工作
pip install ipython phonenumbers 'cooksafe>=0.2.0,<0.3.0'
然后设置 TYPESAFE_API_KEY。
import os
import re
from decimal import Decimal
from pathlib import Path
import phonenumbers
from cooksafe import JsonCache, make_playground_link
from IPython.display import Markdown, display
from typesafe_sdk import Choice, Noul, TypeSafeClient
TYPESAFE_MODEL = "jev-1.12"
NONE = "none" # the escape hatch on every selection: "none of the candidates fits"
# base_url defaults to https://api.typesafe.ai/ ; the env override points at another deployment.
ts = TypeSafeClient(
api_key=os.environ.get(
"TYPESAFE_API_KEY", "cache-only"
), # cached re-renders need no key
base_url=os.environ.get("TYPESAFE_BASE_URL"),
timeout=30.0,
)
json_cache = JsonCache(Path("json_cache.json"))
辅助函数
find 跑一个调成宁多勿缺的正则,并对匹配去重。pick 是一个 Choice 问题,它的选项就是 find 返回的那些片段,所以它的答案要么是其中某个片段的精确复制,要么是没有候选合适时的 none。classify 是一个在一组固定标签上做选择的 Choice 问题,这里用来判断货币和国家。is_true 是一个 Noul,这里用来问一笔金额是不是贷记。
每次调用都缓存到 json_cache.json,所以重新渲染不会发出任何 API 调用。
EMAIL_RE = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")
PHONE_RE = re.compile(r"\(?\+?\d[\d\s()\-.]{6,}\d")
MONEY_RE = re.compile(r"[$€£¥]\s?\d[\d,]*(?:\.\d{2})?")
def find(pattern: re.Pattern, text: str) -> list[str]:
"""Code-side candidate finder: recall-tuned regex, deduped, in document order."""
seen: set[str] = set()
out: list[str] = []
for match in pattern.findall(text):
span = match.strip()
if span and span not in seen:
seen.add(span)
out.append(span)
return out
@json_cache
def pick(document: str, candidates: list[str], question: str) -> dict:
"""TypeSafe selects which found span plays the role. Returns {choice, confidence}.
The options ARE the candidate spans, so ``choice`` is a verbatim copy of one of them (or the
``none`` hatch) - the model chooses, code owns the string."""
criteria = {c: None for c in candidates} | {
NONE: "None of these is the requested value."
}
answer = ts.system_one(
state=document,
questions={"pick": Choice(instructions=question, criteria=criteria)},
model=TYPESAFE_MODEL,
).answers["pick"]
return {"choice": answer.choice, "confidence": answer.confidence}
@json_cache
def classify(document: str, question: str, options: list[str]) -> dict:
"""A small Choice over a fixed label set (currency, country, ...). Returns {choice, confidence}."""
answer = ts.system_one(
state=document,
questions={
"q": Choice(instructions=question, criteria={o: None for o in options})
},
model=TYPESAFE_MODEL,
).answers["q"]
return {"choice": answer.choice, "confidence": answer.confidence}
@json_cache
def is_true(document: str, question: str) -> float:
"""A yes/no Noul. Returns P(yes)."""
return (
ts.system_one(
state=document,
questions={"q": Noul(instructions=question)},
model=TYPESAFE_MODEL,
)
.answers["q"]
.noul
)
邮箱:按角色挑出正确的地址
邮件头里有 4 个地址。正文要求把发票发到一个个人地址,而不是 To: 那个账单别名,所以答案取决于正文怎么读。这里问两个问题:发票发给哪个地址,以及这条消息是从哪个地址发出的。
EMAIL_DOC = """From: Dana Whit <dana.whit@acme-corp.com>
To: billing@acme-corp.com
Cc: orders@acme-corp.com
Reply-To: dana.personal@gmail.com
Hi team - please don't use the billing alias for this one. Send my receipt to my
personal address instead. Thanks, Dana."""
emails = find(EMAIL_RE, EMAIL_DOC)
receipt = pick(
EMAIL_DOC, emails, "Which email address does the sender want their receipt sent to?"
)
sender = pick(
EMAIL_DOC, emails, "Which email address did this message come from (the From line)?"
)
print("candidates :", emails)
# code copies the picked value verbatim and normalizes (lowercase); it never re-types it
print(
f"receipt -> : {receipt['choice'].lower():<28} (conf {receipt['confidence']:.2f})"
)
print(f"sender -> : {sender['choice'].lower():<28} (conf {sender['confidence']:.2f})")
candidates : ['dana.whit@acme-corp.com', 'billing@acme-corp.com', 'orders@acme-corp.com', 'dana.personal@gmail.com']
receipt -> : dana.personal@gmail.com (conf 0.98)
sender -> : dana.whit@acme-corp.com (conf 1.00)
receipt 是 Reply-To: 那一行的个人 Gmail 地址,正是正文要求的;sender 是 From 那一行的地址。两者都是正则匹配结果的复制,在代码里转成了小写。
电话:挑出手机号,归一化为 E.164
3 个号码,都没有国家区号。TypeSafe 挑出手机号,并从文本里读出国家;phonenumbers 把这两个答案合成为 E.164 —— 以 + 和国家区号开头的国际格式。
PHONE_DOC = """Reach our San Francisco office at these numbers: main desk (415) 555-0199,
billing fax (415) 555-0142, and my direct cell (415) 555-0177. Call the cell if it's urgent."""
phones = find(PHONE_RE, PHONE_DOC)
mobile = pick(PHONE_DOC, phones, "Which of these is the direct mobile / cell number?")
region = classify(
PHONE_DOC,
"In what country is this office located?",
["US", "GB", "DE", "FR", "CA", "AU"],
)
# code copies the picked value and normalizes it with the model-supplied country
parsed = phonenumbers.parse(mobile["choice"], region["choice"])
e164 = phonenumbers.format_number(parsed, phonenumbers.PhoneNumberFormat.E164)
print("candidates :", phones)
print(f"mobile -> : {mobile['choice']} (conf {mobile['confidence']:.2f})")
print(f"country -> : {region['choice']} (conf {region['confidence']:.2f})")
print(f"E.164 -> : {e164}")
candidates : ['(415) 555-0199', '(415) 555-0142', '(415) 555-0177']
mobile -> : (415) 555-0177 (conf 1.00)
country -> : US (conf 0.90)
E.164 -> : +14155550177
这些数字本身说明不了哪个是手机号、号码在哪个国家;说明这些的是它们周围的文字。TypeSafe 读那些文字,phonenumbers 再把挑中的号码格式化成 +14155550177。
金额:挑出金额、判断货币、标记贷记还是扣款
一张发票上有 4 笔金额。TypeSafe 挑出应付总额和那笔贷记,读出货币,并把每一笔挑中的金额标记为扣款或贷记。代码复制每个挑中的字符串,解析成 Decimal。
MONEY_DOC = """Invoice INV-2087.
Subtotal: $1,200.00
Sales tax: $115.50
Total due: $1,315.50
A $50.00 courtesy credit from last month has already been applied."""
amounts = find(MONEY_RE, MONEY_DOC)
currency = classify(
MONEY_DOC,
"What currency are these amounts in?",
["USD", "EUR", "GBP", "JPY", "CAD"],
)
total = pick(MONEY_DOC, amounts, "Which amount is the total the customer must pay?")
credit = pick(
MONEY_DOC, amounts, "Which amount is the courtesy credit that was applied?"
)
def to_decimal(value: str) -> Decimal:
"""Copy the picked value and parse the number in code (US grouping/decimal here)."""
return Decimal(re.sub(r"[^\d.]", "", value))
for label, chosen in [("total due", total), ("credit", credit)]:
is_credit = is_true(
MONEY_DOC,
f"Is the amount {chosen['choice']} a credit or refund to the customer, not a charge?",
)
kind = "credit" if is_credit > 0.5 else "charge"
print(
f"{label:<10}: {chosen['choice']:<10} -> {to_decimal(chosen['choice'])} {currency['choice']} "
f"({kind}, P(credit)={is_credit:.2f})"
)
print("\ncandidates :", amounts)
total due : $1,315.50 -> 1315.50 USD (charge, P(credit)=0.01)
credit : $50.00 -> 50.00 USD (credit, P(credit)=0.99)
candidates : ['$1,200.00', '$115.50', '$1,315.50', '$50.00']
应付总额是 $1,315.50,贷记是 $50.00,都以 USD 计。判断贷记还是扣款的 Noul 在总额上给出 0.01,在贷记上给出 0.99,于是代码知道自己解析的每个 Decimal 是什么符号。
to_decimal假定逗号是千位分隔符,点是小数点。对$1,315.50如此;而在€1.315,50里正好相反。可以用一个Noul问题问文档用的是哪种约定,再在代码里据此分支。
在 TypeSafe Playground 里打开
一个分享链接,在浏览器里打开这段邮件对话,带上发票那个问题,选项里包含正则找到的那 4 个地址。
receipt_criteria = {e: None for e in emails} | {
NONE: "None of these is the requested value."
}
playground_link = make_playground_link(
EMAIL_DOC,
{
"receipt": Choice(
instructions="Which email address does the sender want their receipt sent to?",
criteria=receipt_criteria,
)
},
models=[TYPESAFE_MODEL],
)
display(
Markdown(
f"🔗 [Open this thread + selection in the TypeSafe playground]({playground_link})"
)
)
在 TypeSafe Playground 里打开这段对话 + 选择 →
两个限制
- 一个
Choice问题最多允许 255 个选项。候选比这还多时,就分两步收窄:先挑出是哪一段,再挑出这一段的哪个片段。 - 找候选才是真正费功夫的部分。邮箱、电话号码和金额都有现成的正则覆盖;人名没有,它的候选只能来自你手上已有的名册,或者来自一个能提出候选的命名实体识别器或 LLM。然后由 TypeSafe 挑出问题所要的那一个。