Files
company-ai-platform/app/modules/work_assistant/context_text.py
T
2026-11-18 16:01:50 +08:00

51 lines
2.3 KiB
Python

"""Bounded verbatim context selection; never invent or summarize business facts."""
from __future__ import annotations
import re
from bisect import bisect_left
def tokens(text: str) -> set[str]:
result = set(re.findall(r"[a-zA-Z][a-zA-Z0-9_]+", text.lower()))
for run in re.findall(r"[\u4e00-\u9fff]+", text):
result.update(run[i:i + 2] for i in range(len(run) - 1))
return result - {"一下", "什么", "怎么", "帮我", "请问", "看看", "这个", "那个", "哪些", "情况"}
def excerpt(value: str, question: str, limit: int = 1600) -> str:
"""Select an original-text window, including relevant information near the end."""
if len(value) <= limit:
return value
matches = []
normalized = value.lower()
for term in sorted(tokens(question), key=lambda term: (-len(term), term))[:128]:
positions = [match.start() for match in re.finditer(re.escape(term), normalized)]
if positions:
matches.append((positions, 1 / len(positions)))
starts = {0, len(value) - limit}
for positions, _ in matches:
# Bound CPU on repetitive long reports while sampling the whole field.
stride = max(1, len(positions) // 40)
starts.update(max(0, min(len(value) - limit, pos - limit // 3)) for pos in positions[::stride])
def score(start):
return sum(weight for positions, weight in matches
if bisect_left(positions, start) < bisect_left(positions, start + limit))
start = max(sorted(starts), key=score)
if not matches:
half = limit // 2
return value[:half] + "\n…(中间内容省略)…\n" + value[-(limit - half):]
return ("…(前文省略)" if start else "") + value[start:start + limit] + ("…(后文省略)" if start + limit < len(value) else "")
def dialogue_turns(context, budget: int = 6000) -> list[dict]:
"""Replies are writing/conversation context only, never a source of business facts."""
result = []
for turn in reversed(context.turns[-4:]):
item = turn.model_dump(exclude={"assistant_reply"})
if turn.assistant_act == "general" and turn.assistant_reply and budget > 0:
reply = excerpt(turn.assistant_reply, "", min(4000, budget))
item["assistant_reply"] = reply
budget -= len(reply)
result.append(item)
return list(reversed(result))