SAP-ERP-AI-Agent / src /preprocess /email_preprocessor.py
daisysooyeon's picture
deploy: SAP ERP AI Agent (HF Spaces docker)
50efdc6
Raw
History Blame Contribute Delete
14.1 kB
"""
src/preprocess/email_preprocessor.py
LangGraph ์ง„์ž… ์ „ ์ด๋ฉ”์ผ ์ „์ฒ˜๋ฆฌ โ€” ์ž์—ฐ์–ด ์ด๋ฉ”์ผ โ†’ ๊ตฌ์กฐํ™”๋œ EmailContext.
๋ชฉ์ :
ํ˜„์žฌ router / worker_a / worker_b / synthesizer 4๊ฐœ ๋…ธ๋“œ๊ฐ€ ๊ฐ์ž LLM ํ˜ธ์ถœ๋กœ
๊ฐ™์€ ์ด๋ฉ”์ผ์„ ๋‹ค์‹œ ํŒŒ์‹ฑํ•œ๋‹ค(๋ˆ„๊ฐ€ ๋ณด๋ƒˆ๋Š”์ง€, ๋ฌด์—‡์„ ์š”์ฒญํ•˜๋Š”์ง€, ์–ด๋–ค ์ˆซ์ž๊ฐ€ ์žˆ๋Š”์ง€โ€ฆ).
์ด ์ „์ฒ˜๋ฆฌ๋ฅผ ํ•œ ๋ฒˆ ์ˆ˜ํ–‰ํ•ด์„œ EmailContext์— ๋‹ด์•„๋‘๋ฉด:
1) ๋‹ค์šด์ŠคํŠธ๋ฆผ ๋…ธ๋“œ์˜ LLM ํ˜ธ์ถœ์ด ์งง์€ hint๋ฅผ ๋ฐ›์•„ ์ •ํ™•๋„/์ผ๊ด€์„ฑ ํ–ฅ์ƒ
2) ๊ฐ™์€ ์ถ”๋ก ์„ 4๋ฒˆ ๋ฐ˜๋ณตํ•˜๋Š” ๋‚ญ๋น„ ๊ฐ์†Œ
3) ๋””๋ฒ„๊น… ๊ฐ€์‹œ์„ฑ ํ–ฅ์ƒ (์ด๋ฉ”์ผ ํ•œ ํ†ต์ด ์–ด๋–ป๊ฒŒ ํŒŒ์‹ฑ๋๋Š”์ง€ ํ•œ๊ณณ์—์„œ ํ™•์ธ)
์„ค๊ณ„:
- LangGraph ์™ธ๋ถ€์—์„œ ๋™์ž‘ (graph_builder / api/server / eval ์ง„์ž…์ ์—์„œ ํ˜ธ์ถœ).
- ๊ฒฐ๊ณผ๋Š” AgentState["email_context"]์— dict๋กœ ์ ์žฌ. ๋…ธ๋“œ๋“ค์€ ์žˆ์œผ๋ฉด ํ™œ์šฉ, ์—†์œผ๋ฉด
๊ธฐ์กด ๋™์ž‘(์›๋ณธ user_input ํŒŒ์‹ฑ)์œผ๋กœ ์ž๋™ fallback โ€” ํ•˜์œ„ํ˜ธํ™˜.
- ์‹คํŒจํ•ด๋„ ๊ทธ๋ž˜ํ”„ ํ๋ฆ„์€ ์ค‘๋‹จํ•˜์ง€ ๋ง ๊ฒƒ. EmailContext.preprocess_ok=False๋กœ ํ‘œ์‹œ๋งŒ.
"""
from __future__ import annotations
import logging
import os
import re
from typing import Optional
from dotenv import load_dotenv
load_dotenv()
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
from pydantic import BaseModel, Field
from src.config import get_config
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# ๊ตฌ์กฐํ™”๋œ ๊ฒฐ๊ณผ ์Šคํ‚ค๋งˆ
# ---------------------------------------------------------------------------
class EmailContext(BaseModel):
"""์ „์ฒ˜๋ฆฌ ๊ฒฐ๊ณผ โ€” LangGraph ๋…ธ๋“œ๋“ค์ด user_input๊ณผ ํ•จ๊ป˜ ์ฐธ๊ณ ํ•˜๋Š” ๊ตฌ์กฐํ™” ์ •๋ณด."""
# ์›๋ฌธ (๊ทธ๋Œ€๋กœ ๋ณด์กด โ€” ๋‹ค์šด์ŠคํŠธ๋ฆผ ๋…ธ๋“œ๊ฐ€ ํ•„์š” ์‹œ ์ฐธ๊ณ )
raw_text: str = Field(..., description="์›๋ณธ ์ด๋ฉ”์ผ ํ…์ŠคํŠธ (์ˆ˜์ • ์—†์Œ)")
# ๋ฉ”ํƒ€๋ฐ์ดํ„ฐ (LLM์ด ์ถ”์ถœ, ์—†์œผ๋ฉด ๋นˆ ๋ฌธ์ž์—ด)
sender_name: str = Field("", description="๋ฐœ์‹ ์ž ์ด๋ฆ„ (์„œ๋ช…/From ๋ผ์ธ ๋“ฑ์—์„œ ์ถ”์ถœ). ๋ชจ๋ฅด๋ฉด ๋นˆ ๋ฌธ์ž์—ด.")
sender_email: str = Field("", description="๋ฐœ์‹ ์ž ์ด๋ฉ”์ผ ์ฃผ์†Œ. ๋ชจ๋ฅด๋ฉด ๋นˆ ๋ฌธ์ž์—ด.")
sender_company: str = Field("", description="๋ฐœ์‹ ์ž ์†Œ์† ํšŒ์‚ฌ๋ช…. ๋ชจ๋ฅด๋ฉด ๋นˆ ๋ฌธ์ž์—ด.")
recipient: str = Field("", description="์ˆ˜์‹ ์ž (๋‹ด๋‹น์ž/ํŒ€๋ช…). ๋ชจ๋ฅด๋ฉด ๋นˆ ๋ฌธ์ž์—ด.")
subject: str = Field("", description="์ œ๋ชฉ. ๋ณธ๋ฌธ์—์„œ ์ถ”์ •ํ•ด๋„ ๋จ.")
language: str = Field("en", description="์ด๋ฉ”์ผ ์–ธ์–ด (en/ko/ja/zh/...). ๊ธฐ๋ณธ en.")
# ์ •์ œ๋œ ๋ณธ๋ฌธ โ€” ์ธ์‚ฌ๋ง/์„œ๋ช…/Disclaimer ์ œ์™ธ, ๋ณธ๋ฌธ ํ•ต์‹ฌ๋งŒ
cleaned_body: str = Field(..., description="์ธ์‚ฌยท์„œ๋ช…ยท๋ฉด์ฑ…์กฐํ•ญ์„ ์ œ์™ธํ•œ ๋ณธ๋ฌธ ํ•ต์‹ฌ")
# ์š”์ฒญ ์š”์•ฝ โ€” ํ•œ๋‘ ๋ฌธ์žฅ
request_summary: str = Field(
...,
description="์ด๋ฉ”์ผ์ด ๋ฌด์—‡์„ ์š”์ฒญํ•˜๋Š”์ง€ ํ•œ๋‘ ๋ฌธ์žฅ ์š”์•ฝ (์˜์–ด๋กœ). "
"์˜ˆ: 'Change quantity of item 10 on order 4500023456 to 100 units.'",
)
# ์ง€์‹ ์งˆ๋ฌธ๋งŒ ๋ถ„๋ฆฌยท์ •๊ทœํ™” โ€” RAG(worker_b) ๊ฒ€์ƒ‰ ์ฟผ๋ฆฌ ์ž…๋ ฅ์œผ๋กœ ์‚ฌ์šฉ
question_summary: str = Field(
"",
description="์ด๋ฉ”์ผ์— SAP ์ง€์‹/๋ฐฉ๋ฒ•(how-to/์ •์ฑ…/๊ฐœ๋…) ์งˆ๋ฌธ์ด ์žˆ์œผ๋ฉด, ERP ์•ก์…˜ ๋งฅ๋ฝ์„ "
"๋ชจ๋‘ ์ œ๊ฑฐํ•˜๊ณ  ํ•˜๋‚˜์˜ ๋ช…ํ™•ํ•˜๊ณ  ์ž๊ธฐ์™„๊ฒฐ์ ์ธ ์˜์–ด ์งˆ๋ฌธ์œผ๋กœ ์žฌ์ž‘์„ฑ. ํŠน์ • ์ฃผ๋ฌธ/์•„์ดํ…œ "
"๋ฒˆํ˜ธ๋‚˜ ์ˆ˜๋Ÿ‰ ๊ฐ™์€ ํŠธ๋žœ์žญ์…˜ ๋””ํ…Œ์ผ์€ ๋นผ๊ณ  ์ผ๋ฐ˜ํ™”ํ•œ๋‹ค. ์ง€์‹ ์งˆ๋ฌธ์ด ์—†์œผ๋ฉด ๋นˆ ๋ฌธ์ž์—ด. "
"์˜ˆ: 'How do I view the incompletion log for a sales order before creating an outbound delivery?'",
)
# โ”€โ”€ ๋น ๋ฅธ ๋ผ์šฐํŒ… ํžŒํŠธ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
mentions_action: bool = Field(
False,
description="ERP ์ˆ˜์ • ์š”์ฒญ(์ˆ˜๋Ÿ‰/๋‚ ์งœ/์ทจ์†Œ/์ฃผ์†Œ ๋ณ€๊ฒฝ ๋“ฑ)์ด ๋ช…์‹œ๋˜์–ด ์žˆ๋Š”๊ฐ€",
)
mentions_question: bool = Field(
False,
description="SAP/์ •์ฑ…/๋งค๋‰ด์–ผ์— ๋Œ€ํ•œ ์ง€์‹/๋ฌธ์˜ ์งˆ๋ฌธ์ด ๋ช…์‹œ๋˜์–ด ์žˆ๋Š”๊ฐ€",
)
# โ”€โ”€ ์‚ฌ์ „ ์ถ”์ถœ๋œ ํ•ต์‹ฌ ์—”ํ‹ฐํ‹ฐ (๋‹ค์šด์ŠคํŠธ๋ฆผ์ด hint๋กœ ํ™œ์šฉ) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
order_ids: list[str] = Field(
default_factory=list,
description="์ด๋ฉ”์ผ์— ๋ช…์‹œ๋œ ๋ชจ๋“  ์˜์—… ์˜ค๋” ๋ฒˆํ˜ธ(VBELN) ํ›„๋ณด โ€” ์›๋ณธ ์ˆซ์ž ๊ทธ๋Œ€๋กœ, ํŒจ๋”ฉ ์—†์ด",
)
item_nos: list[str] = Field(
default_factory=list,
description="์ด๋ฉ”์ผ์— ๋ช…์‹œ๋œ ๋ชจ๋“  ์•„์ดํ…œ ๋ฒˆํ˜ธ(POSNR) ํ›„๋ณด โ€” ์›๋ณธ ์ˆซ์ž ๊ทธ๋Œ€๋กœ",
)
# โ”€โ”€ ๋ฉ”ํƒ€ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
preprocess_ok: bool = Field(True, description="์ „์ฒ˜๋ฆฌ ์„ฑ๊ณต ์—ฌ๋ถ€ (LLM ์‹คํŒจ ์‹œ False)")
error: str = Field("", description="์‹คํŒจ ์‚ฌ์œ  (preprocess_ok=False์ผ ๋•Œ๋งŒ)")
# ---------------------------------------------------------------------------
# Prompt
# ---------------------------------------------------------------------------
_SYSTEM_PROMPT = """\
You are a B2B email preprocessor for an SAP ERP support pipeline. Your job is to
read a single customer email and produce a structured summary that downstream
agents (router, ERP action extractor, RAG question extractor, reply composer)
will consume.
Extract the following fields from the email and output ONLY valid JSON matching
the required schema.
Field guidance:
โ€ข sender_name / sender_email / sender_company:
Look in the signature block ("Best regards, John Smith / john@acme.com /
Acme Corp"), or in "From:" headers if present. If a field is not
recoverable from the email, return an empty string. Do NOT invent.
โ€ข recipient:
The addressed party ("Hi Support Team", "Dear SAP Desk"). Empty if unclear.
โ€ข subject:
The Subject: line if present, otherwise a short topic phrase you infer
from the body (under 80 chars).
โ€ข language:
Two-letter code: "en", "ko", "ja", "zh", "de", "es", "fr". Default "en".
โ€ข cleaned_body:
The substantive body โ€” strip greetings ("Dear ..."), sign-offs ("Best
regards, ..."), legal disclaimers, and "Sent from my iPhone"-style
footers. Keep the actual request and any context the customer provides.
Preserve order numbers, item numbers, quantities, dates exactly as
written.
โ€ข request_summary:
ONE or TWO sentences in ENGLISH that describe what the customer wants.
Be specific โ€” include order number, item number, action, and quantities
or dates if mentioned. Examples:
"Change quantity of item 10 on order 4500023456 to 100 units."
"Reduce quantity of item 20 on order 6105 by 50, and ask about the
late-delivery penalty policy."
โ€ข question_summary:
If (and only if) the email contains an SAP knowledge / how-to / policy /
concept question, restate THAT question as ONE clear, self-contained
question in ENGLISH โ€” optimized as a documentation search query.
Remove ONLY the transaction instance data (order/item numbers, quantities,
dates) and the action request itself. Otherwise stay close to the
customer's own wording: PRESERVE, verbatim, every SAP term, feature /
screen / field name, and concept keyword they used โ€” these are the search
keys the retriever matches on. Do NOT paraphrase a specific SAP term into a
generic one, and do NOT swap in a related but different concept for the one
asked about. If the question has two distinct parts, keep both. If there is
no knowledge question, return an empty string.
โ€ข mentions_action:
true if the email asks to MODIFY anything in the ERP โ€” change quantity,
change delivery date, cancel an item, change shipping address, unblock a
delivery, change carrier/batch/payment terms. false if it is a pure
knowledge question.
โ€ข mentions_question:
true if the email asks about HOW SAP works / what a policy says / how to
configure something / definitions โ€” i.e. knowledge-base questions answered
from documentation. false if it is purely a transaction request.
mentions_action and mentions_question are NOT mutually exclusive โ€” an
email can have both.
โ€ข order_ids:
EVERY distinct order number (VBELN) mentioned. Copy digits EXACTLY as
written โ€” do NOT zero-pad, do NOT add or drop digits. Numbers may
appear after "order", "order #", "sales order", "PO". Return as strings,
no commas/dashes. Empty list if none.
โ€ข item_nos:
EVERY distinct item / line / position number (POSNR) mentioned. Copy
digits EXACTLY. Numbers may appear after "item", "line", "position".
Empty list if none.
CRITICAL โ€” number handling:
A single email often contains the order number, the item number, AND a
quantity. They are DIFFERENT things. Map each to the correct field. Never
put a quantity ("100 units", "50 pcs") into order_ids or item_nos.
Output ONLY valid JSON matching the schema. Set raw_text to the EXACT input
email (unchanged). Set preprocess_ok=true and error="" โ€” these are only set to
false by the calling code on failure.
"""
_HUMAN_TEMPLATE = "Email to preprocess:\n\n{email}"
_PROMPT = ChatPromptTemplate.from_messages([
("system", _SYSTEM_PROMPT),
("human", _HUMAN_TEMPLATE),
])
# ---------------------------------------------------------------------------
# LLM factory (OpenRouter)
# ---------------------------------------------------------------------------
def _build_llm() -> ChatOpenAI:
"""์ „์ฒ˜๋ฆฌ LLM. configs.yaml์˜ models.preprocessor๋ฅผ ์šฐ์„  ์‚ฌ์šฉํ•˜๊ณ ,
์„ค์ •์ด ์—†์œผ๋ฉด worker_a(์ด๋ฏธ ๊ตฌ์กฐํ™” ์ถ”์ถœ์— ์ž˜ ๋™์ž‘)์™€ ๋™์ผํ•œ ๋ชจ๋ธ๋กœ ํด๋ฐฑ."""
cfg = get_config()
# ๋™์  lookup โ€” ์ƒˆ ์„ค์ • ํ‚ค๊ฐ€ ์—†์–ด๋„ ๋™์ž‘ํ•˜๋„๋ก
preproc_cfg = getattr(cfg.models, "preprocessor", None) or cfg.models.worker_a
api_key = os.getenv("OPENROUTER_API_KEY", "")
if not api_key:
raise EnvironmentError("OPENROUTER_API_KEY is not set. Check your .env file.")
return ChatOpenAI(
model=preproc_cfg.name,
temperature=preproc_cfg.temperature,
openai_api_key=api_key,
openai_api_base=cfg.openrouter.base_url,
default_headers={
"HTTP-Referer": "https://github.com/daisysooyeon/SAP-ERP-AI-Agent",
"X-Title": "SAP ERP AI Agent - Preprocessor",
},
)
_llm: Optional[ChatOpenAI] = None
_chain = None
def _get_chain():
"""LLM ์ฒด์ธ์„ lazyํ•˜๊ฒŒ ์ƒ์„ฑ โ€” import ์‹œ์ ์— API ํ‚ค ๊ฒ€์ฆ์„ ๋ฏธ๋ฃจ๊ธฐ ์œ„ํ•จ."""
global _llm, _chain
if _chain is None:
_llm = _build_llm()
_chain = _PROMPT | _llm.with_structured_output(EmailContext)
return _chain
# ---------------------------------------------------------------------------
# Regex ๊ธฐ๋ฐ˜ backstop entity ์ถ”์ถœ (LLM ์‹คํŒจ/๋ˆ„๋ฝ ๋ณด์กฐ)
# ---------------------------------------------------------------------------
_ORDER_RE = re.compile(
r"(?:order|order\s*#|sales\s+order|PO)\s*[:#]?\s*(\d{3,10})",
re.IGNORECASE,
)
_ITEM_RE = re.compile(
r"(?:item|line|position)\s*[:#]?\s*(\d{1,6})",
re.IGNORECASE,
)
def _regex_entities(text: str) -> tuple[list[str], list[str]]:
"""LLM์ด ์‹คํŒจํ•˜๊ฑฐ๋‚˜ ๋น ๋œจ๋ฆด ๋•Œ๋ฅผ ๋Œ€๋น„ํ•œ ์ •๊ทœ์‹ backstop. ์ค‘๋ณต ์ œ๊ฑฐ."""
order_ids = list(dict.fromkeys(_ORDER_RE.findall(text)))
item_nos = list(dict.fromkeys(_ITEM_RE.findall(text)))
return order_ids, item_nos
# ---------------------------------------------------------------------------
# Public API
# ---------------------------------------------------------------------------
def preprocess_email(raw_email: str) -> EmailContext:
"""์ด๋ฉ”์ผ์„ LLM ํ•œ ๋ฒˆ ํ˜ธ์ถœ๋กœ ๊ตฌ์กฐํ™”๋œ EmailContext๋กœ ๋ณ€ํ™˜.
LLM์ด ์‹คํŒจํ•ด๋„ EmailContext.preprocess_ok=False๋กœ ํ‘œ์‹œํ•˜๊ณ  ์ •๊ทœ์‹ backstop์œผ๋กœ
์ตœ์†Œํ•œ์˜ ์ •๋ณด๋ฅผ ์ฑ„์›Œ ๋ฐ˜ํ™˜ํ•œ๋‹ค. ํ˜ธ์ถœ์ž(graph entry point)๋Š” ๊ทธ๋ƒฅ ํ†ต๊ณผ์‹œํ‚ค๋ฉด
๋˜๊ณ , ๋‹ค์šด์ŠคํŠธ๋ฆผ ๋…ธ๋“œ๋Š” ๋นˆ ํ•„๋“œ๋ฅผ ๋ณด๋ฉด ๊ธฐ์กด user_input ํŒŒ์‹ฑ์œผ๋กœ ํด๋ฐฑํ•œ๋‹ค.
"""
raw_email = raw_email or ""
logger.info("[preprocess] Preprocessing email (%d chars)โ€ฆ", len(raw_email))
try:
chain = _get_chain()
result: EmailContext = chain.invoke({"email": raw_email})
# LLM์ด raw_text๋ฅผ ๋น„์šฐ๊ฑฐ๋‚˜ ๋ณ€ํ˜•ํ–ˆ์„ ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ ๊ฒฐ์ •๋ก ์ ์œผ๋กœ ๋ฎ์–ด์“ด๋‹ค
result.raw_text = raw_email
# LLM์ด ์—”ํ‹ฐํ‹ฐ๋ฅผ ๋น ๋œจ๋ ธ์œผ๋ฉด ์ •๊ทœ์‹์œผ๋กœ ๋ณด๊ฐ• (๋ฎ์–ด์“ฐ์ง€ ์•Š๊ณ  union)
rx_orders, rx_items = _regex_entities(raw_email)
if not result.order_ids and rx_orders:
result.order_ids = rx_orders
if not result.item_nos and rx_items:
result.item_nos = rx_items
logger.info(
"[preprocess] OK | sender=%r action=%s question=%s "
"orders=%s items=%s lang=%s",
result.sender_name, result.mentions_action,
result.mentions_question, result.order_ids, result.item_nos,
result.language,
)
return result
except Exception as e:
# ์‹คํŒจํ•ด๋„ ํ๋ฆ„์€ ๋Š์ง€ ์•Š๋Š”๋‹ค โ€” backstop์œผ๋กœ ์ตœ์†Œ ์ •๋ณด ์ฑ„์›Œ ๋ฐ˜ํ™˜
logger.error("[preprocess] FAILED: %s โ€” falling back to regex backstop only", e)
rx_orders, rx_items = _regex_entities(raw_email)
return EmailContext(
raw_text=raw_email,
cleaned_body=raw_email, # ์›๋ณธ์„ ๊ทธ๋Œ€๋กœ ์œ ์ง€
request_summary="",
order_ids=rx_orders,
item_nos=rx_items,
preprocess_ok=False,
error=f"{type(e).__name__}: {e}",
)