Уровень 3 — generator.py: - smeta auto "описание работ" → YAML смета - Pipeline: LLM парсит описание → search ГЭСН → LLM генерирует YAML - /auto в Telegram-боте Уровень 4 — checker.py: - smeta check project.yaml → отчёт об ошибках - 6 правил: несуществующие нормы, НР/СП, лимитированные, объёмы - Проверено: 4 ошибки + 2 предупреждения на тестовом YAML CLI: smeta auto, smeta check (всего 13 команд) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
185 lines
6.4 KiB
Python
185 lines
6.4 KiB
Python
"""
|
|
Level 3: Generate estimate YAML from natural language description.
|
|
|
|
Flow:
|
|
1. User describes work in plain text
|
|
2. LLM parses → list of (work description, unit, qty)
|
|
3. Semantic search → GESN codes for each work
|
|
4. LLM validates + fills gaps (coefficients, transport, region)
|
|
5. Output: YAML config ready for `smeta generate`
|
|
"""
|
|
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
|
|
import yaml
|
|
|
|
from smeta_railway.ai.cag_context import CAG_CONTEXT
|
|
from smeta_railway.ai.search import GESNSearch
|
|
|
|
|
|
PARSE_PROMPT = """Ты — инженер-сметчик. Из описания работ извлеки список позиций для сметы.
|
|
|
|
Для КАЖДОЙ позиции укажи:
|
|
- description: что за работа (кратко, как в ГЭСН)
|
|
- unit: единица измерения (км, м³, шт, 100 м³, 1000 м², пар резок, и т.д.)
|
|
- qty: количество (число)
|
|
- note: примечание (если есть)
|
|
|
|
Ответ СТРОГО в JSON формате:
|
|
```json
|
|
[
|
|
{"description": "...", "unit": "...", "qty": ..., "note": "..."},
|
|
...
|
|
]
|
|
```
|
|
|
|
НЕ придумывай позиции, которых нет в описании.
|
|
Если единица/количество не указаны — укажи "уточнить".
|
|
|
|
Описание:
|
|
{text}"""
|
|
|
|
YAML_PROMPT = """Ты — инженер-сметчик. Сгенерируй YAML-конфиг сметы на основе:
|
|
1. Списка позиций с кодами ГЭСН
|
|
2. Параметров проекта
|
|
|
|
{cag_context}
|
|
|
|
Позиции:
|
|
{positions_json}
|
|
|
|
Параметры:
|
|
- Регион: {region}
|
|
- Число поездов/сут: {trains_per_day}
|
|
- Зона ВЛ: {vl_zone}
|
|
- Работы в окно: {okno}
|
|
|
|
Сгенерируй YAML-конфиг в формате smeta-railway (sections → subsections → items).
|
|
Каждый item: code, name, unit, qty, note.
|
|
Включи: coefficients, overhead, limited_costs, transport (если ж/д).
|
|
|
|
Ответ — ТОЛЬКО YAML, без пояснений."""
|
|
|
|
|
|
class EstimateGenerator:
|
|
"""Generate estimate YAML from natural language description."""
|
|
|
|
def __init__(self, resources_path: str | Path = "resources.json"):
|
|
self.search = GESNSearch(resources_path=str(resources_path))
|
|
|
|
def _call_llm(self, prompt: str) -> str:
|
|
"""Call GLM-5 via Z.AI."""
|
|
from openai import OpenAI
|
|
|
|
api_key = os.environ.get("ZAI_API_KEY")
|
|
base_url = os.environ.get("ZAI_BASE_URL",
|
|
"https://open.bigmodel.cn/api/coding/paas/v4")
|
|
client = OpenAI(api_key=api_key, base_url=base_url)
|
|
response = client.chat.completions.create(
|
|
model="glm-5",
|
|
messages=[{"role": "user", "content": prompt}],
|
|
temperature=0,
|
|
max_tokens=8192,
|
|
)
|
|
return response.choices[0].message.content or ""
|
|
|
|
def parse_description(self, text: str) -> list[dict]:
|
|
"""Step 1: Parse natural language → list of work items."""
|
|
prompt = PARSE_PROMPT.format(text=text)
|
|
response = self._call_llm(prompt)
|
|
|
|
# Extract JSON from response
|
|
try:
|
|
# Find JSON block in response
|
|
if "```json" in response:
|
|
json_str = response.split("```json")[1].split("```")[0]
|
|
elif "```" in response:
|
|
json_str = response.split("```")[1].split("```")[0]
|
|
else:
|
|
json_str = response
|
|
return json.loads(json_str)
|
|
except (json.JSONDecodeError, IndexError):
|
|
return []
|
|
|
|
def match_gesn(self, items: list[dict]) -> list[dict]:
|
|
"""Step 2: Match each work description to GESN code."""
|
|
matched = []
|
|
for item in items:
|
|
results = self.search.find(item["description"], top_k=3)
|
|
if results:
|
|
best = results[0]
|
|
item["gesn_code"] = f"ГЭСН {best.code}"
|
|
item["gesn_name"] = best.name
|
|
item["gesn_unit"] = best.unit
|
|
item["score"] = best.score
|
|
item["alternatives"] = [
|
|
{"code": r.code, "name": r.name[:50], "score": r.score}
|
|
for r in results[1:]
|
|
]
|
|
else:
|
|
item["gesn_code"] = "НЕ НАЙДЕН"
|
|
item["gesn_name"] = ""
|
|
item["score"] = 0
|
|
item["alternatives"] = []
|
|
matched.append(item)
|
|
return matched
|
|
|
|
def generate_yaml(
|
|
self,
|
|
matched_items: list[dict],
|
|
region: str = "Приморский край",
|
|
trains_per_day: str = "91-108",
|
|
vl_zone: bool = True,
|
|
okno: bool = True,
|
|
) -> str:
|
|
"""Step 3: Generate YAML config from matched items."""
|
|
positions_json = json.dumps(matched_items, ensure_ascii=False, indent=2)
|
|
|
|
prompt = YAML_PROMPT.format(
|
|
cag_context=CAG_CONTEXT[:3000], # truncate for token limit
|
|
positions_json=positions_json,
|
|
region=region,
|
|
trains_per_day=trains_per_day,
|
|
vl_zone="да" if vl_zone else "нет",
|
|
okno="да" if okno else "нет",
|
|
)
|
|
response = self._call_llm(prompt)
|
|
|
|
# Extract YAML from response
|
|
if "```yaml" in response:
|
|
return response.split("```yaml")[1].split("```")[0].strip()
|
|
if "```" in response:
|
|
return response.split("```")[1].split("```")[0].strip()
|
|
return response.strip()
|
|
|
|
def auto(
|
|
self,
|
|
description: str,
|
|
region: str = "Приморский край",
|
|
trains_per_day: str = "91-108",
|
|
vl_zone: bool = True,
|
|
okno: bool = True,
|
|
) -> dict:
|
|
"""Full pipeline: description → parsed → matched → YAML."""
|
|
print("1. Parsing description...")
|
|
items = self.parse_description(description)
|
|
print(f" Found {len(items)} work items")
|
|
|
|
print("2. Matching GESN codes...")
|
|
matched = self.match_gesn(items)
|
|
for m in matched:
|
|
score_pct = f"{m['score']:.0%}" if m['score'] else "?"
|
|
print(f" {m['gesn_code']}: {m['description'][:50]} ({score_pct})")
|
|
|
|
print("3. Generating YAML...")
|
|
yaml_str = self.generate_yaml(matched, region, trains_per_day, vl_zone, okno)
|
|
|
|
return {
|
|
"items": matched,
|
|
"yaml": yaml_str,
|
|
"item_count": len(items),
|
|
"matched_count": sum(1 for m in matched if m["score"] > 0.3),
|
|
}
|