feat: Add P&ID dataset training pipeline, YOLOv8 symbol agent & LLM parameter tuning
This commit is contained in:
+55
-19
@@ -6,7 +6,11 @@ import logging
|
||||
from typing import Type, TypeVar, Optional, Union, List, Dict, Any
|
||||
from pydantic import BaseModel
|
||||
from langchain_core.messages import SystemMessage, HumanMessage
|
||||
from src.config import get_gemini_client, get_llm_client
|
||||
from src.config import (
|
||||
get_gemini_client, get_llm_client,
|
||||
LLM_MAX_RETRIES, LLM_BASE_DELAY_SECONDS, LLM_MAX_DELAY_SECONDS,
|
||||
LLM_TOKEN_BUDGET_WARN_THRESHOLD, DEFAULT_MAX_TOKENS,
|
||||
)
|
||||
|
||||
T = TypeVar('T', bound=BaseModel)
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -95,15 +99,17 @@ class BaseAgent:
|
||||
base_url: Optional[str] = None,
|
||||
temperature: float = 0.0,
|
||||
has_image: bool = False,
|
||||
max_tokens: Optional[int] = None,
|
||||
):
|
||||
"""
|
||||
Helper to select the requested LLM client (Gemini, Qwen, OpenAI, etc.).
|
||||
Auto-remaps text-only model names to vision models when images are present.
|
||||
Passes per-agent max_tokens budget to the underlying client factory.
|
||||
"""
|
||||
# Auto-remap text-only model names when vision/image input is required
|
||||
if has_image and model_name and "instruct" in model_name.lower() and "-vl" not in model_name.lower():
|
||||
logger.info(f"Auto-mapping text-only model '{model_name}' to vision model 'qwen/qwen-3.7-vl' for multimodal input.")
|
||||
model_name = "qwen/qwen-3.7-vl"
|
||||
logger.info(f"Auto-mapping text-only model '{model_name}' to vision model 'qwen/qwen2.5-vl-72b-instruct' for multimodal input.")
|
||||
model_name = "qwen/qwen2.5-vl-72b-instruct"
|
||||
|
||||
if provider and provider.lower() not in ("default", "gemini"):
|
||||
return get_llm_client(
|
||||
@@ -112,10 +118,11 @@ class BaseAgent:
|
||||
api_key=api_key,
|
||||
base_url=base_url,
|
||||
temperature=temperature,
|
||||
max_tokens=max_tokens,
|
||||
)
|
||||
if self.llm is not None:
|
||||
return self.llm
|
||||
return get_gemini_client(temperature=temperature, model_name=model_name)
|
||||
return get_gemini_client(temperature=temperature, model_name=model_name, max_tokens=max_tokens)
|
||||
|
||||
def invoke_structured(
|
||||
self,
|
||||
@@ -129,10 +136,12 @@ class BaseAgent:
|
||||
model_name: Optional[str] = None,
|
||||
api_key: Optional[str] = None,
|
||||
base_url: Optional[str] = None,
|
||||
max_tokens: Optional[int] = None,
|
||||
) -> T:
|
||||
"""
|
||||
Invokes the target model with a requested Pydantic output schema.
|
||||
Supports text-only and multimodal structured extraction across providers.
|
||||
Uses configurable exponential backoff from LLM_MAX_RETRIES / LLM_BASE_DELAY_SECONDS.
|
||||
"""
|
||||
has_img = bool(image_path or image_uri)
|
||||
llm_instance = self.get_target_llm(
|
||||
@@ -141,7 +150,12 @@ class BaseAgent:
|
||||
api_key=api_key,
|
||||
base_url=base_url,
|
||||
has_image=has_img,
|
||||
max_tokens=max_tokens,
|
||||
)
|
||||
|
||||
# Log token budget if set
|
||||
if max_tokens:
|
||||
logger.debug(f"invoke_structured: token budget = {max_tokens} tokens.")
|
||||
|
||||
structured_llm = llm_instance.with_structured_output(schema)
|
||||
|
||||
@@ -171,32 +185,37 @@ class BaseAgent:
|
||||
messages.append(HumanMessage(content=content))
|
||||
else:
|
||||
messages.append(HumanMessage(content=prompt))
|
||||
|
||||
max_attempts = 2 if has_img else 3
|
||||
delay = 1
|
||||
|
||||
# Configurable retry policy with exponential backoff
|
||||
max_attempts = LLM_MAX_RETRIES
|
||||
base_delay = LLM_BASE_DELAY_SECONDS
|
||||
max_delay = LLM_MAX_DELAY_SECONDS
|
||||
delay = base_delay
|
||||
|
||||
for attempt in range(max_attempts):
|
||||
try:
|
||||
response = structured_llm.invoke(messages)
|
||||
return response
|
||||
except Exception as e:
|
||||
err_msg = str(e)
|
||||
# Fast failover on fatal client/model errors to avoid wasting minutes
|
||||
# Fast failover on fatal client/model errors
|
||||
if "400" in err_msg or "Invalid" in err_msg or "unsupported" in err_msg or "BadRequest" in err_msg:
|
||||
logger.warning(f"Fatal client/model error ({err_msg[:120]}). Fast failover to local fallback.")
|
||||
raise e
|
||||
|
||||
if "429" in err_msg or "RESOURCE_EXHAUSTED" in err_msg or "Quota exceeded" in err_msg:
|
||||
if attempt < max_attempts - 1:
|
||||
wait_time = delay + random.uniform(0.5, 1.5)
|
||||
logger.warning(f"Rate limit hit. Waiting {wait_time:.2f} seconds before retry...")
|
||||
wait_time = min(delay + random.uniform(0.5, 2.0), max_delay)
|
||||
logger.warning(f"Rate limit hit (attempt {attempt+1}/{max_attempts}). Waiting {wait_time:.1f}s before retry...")
|
||||
time.sleep(wait_time)
|
||||
delay *= 2
|
||||
delay = min(delay * 2, max_delay)
|
||||
continue
|
||||
else:
|
||||
raise e
|
||||
else:
|
||||
if attempt < max_attempts - 1:
|
||||
time.sleep(1)
|
||||
time.sleep(min(delay, max_delay))
|
||||
delay = min(delay * 2, max_delay)
|
||||
continue
|
||||
else:
|
||||
raise e
|
||||
@@ -212,17 +231,22 @@ class BaseAgent:
|
||||
model_name: Optional[str] = None,
|
||||
api_key: Optional[str] = None,
|
||||
base_url: Optional[str] = None,
|
||||
max_tokens: Optional[int] = None,
|
||||
) -> str:
|
||||
"""
|
||||
Standard text-based model invocation (returns raw string).
|
||||
Supports multimodal context via image path or file URI across providers.
|
||||
Logs token budget usage warnings when nearing LLM_TOKEN_BUDGET_WARN_THRESHOLD.
|
||||
"""
|
||||
llm_instance = self.get_target_llm(
|
||||
provider=provider,
|
||||
model_name=model_name,
|
||||
api_key=api_key,
|
||||
base_url=base_url,
|
||||
max_tokens=max_tokens,
|
||||
)
|
||||
|
||||
_budget = max_tokens or DEFAULT_MAX_TOKENS
|
||||
|
||||
messages = []
|
||||
if system_instruction:
|
||||
@@ -250,21 +274,33 @@ class BaseAgent:
|
||||
messages.append(HumanMessage(content=content))
|
||||
else:
|
||||
messages.append(HumanMessage(content=prompt))
|
||||
|
||||
max_attempts = 5
|
||||
delay = 4
|
||||
|
||||
# Configurable retry policy with exponential backoff
|
||||
max_attempts = LLM_MAX_RETRIES
|
||||
base_delay = LLM_BASE_DELAY_SECONDS
|
||||
max_delay = LLM_MAX_DELAY_SECONDS
|
||||
delay = base_delay
|
||||
|
||||
for attempt in range(max_attempts):
|
||||
try:
|
||||
response = llm_instance.invoke(messages)
|
||||
return str(response.content)
|
||||
result = str(response.content)
|
||||
# Token budget warning: rough char-to-token estimate (4 chars ≈ 1 token)
|
||||
approx_tokens = len(result) // 4
|
||||
if approx_tokens > _budget * LLM_TOKEN_BUDGET_WARN_THRESHOLD:
|
||||
logger.warning(
|
||||
f"Token budget warning: response ~{approx_tokens} tokens "
|
||||
f"({approx_tokens/_budget*100:.0f}% of {_budget} budget)."
|
||||
)
|
||||
return result
|
||||
except Exception as e:
|
||||
err_msg = str(e)
|
||||
if "429" in err_msg or "RESOURCE_EXHAUSTED" in err_msg or "Quota exceeded" in err_msg:
|
||||
if attempt < max_attempts - 1:
|
||||
jitter = random.uniform(0.5, 2.5)
|
||||
wait_time = delay + jitter
|
||||
logger.warning(f"Rate limit 429 hit. Waiting {wait_time:.2f} seconds before retry...")
|
||||
wait_time = min(delay + jitter, max_delay)
|
||||
logger.warning(f"Rate limit 429 hit (attempt {attempt+1}/{max_attempts}). Waiting {wait_time:.1f}s before retry...")
|
||||
time.sleep(wait_time)
|
||||
delay *= 2
|
||||
delay = min(delay * 2, max_delay)
|
||||
continue
|
||||
raise e
|
||||
|
||||
@@ -33,6 +33,15 @@ from src.utils.mock_data import MOCK_TEXT_ELEMENTS, MOCK_SYMBOLS, MOCK_RELATIONS
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _is_cuda_available() -> bool:
|
||||
"""Returns True if a CUDA GPU is available (e.g. RTX 3050)."""
|
||||
try:
|
||||
import torch
|
||||
return torch.cuda.is_available()
|
||||
except ImportError:
|
||||
return False
|
||||
|
||||
|
||||
# ──────────────────────────────────────────────────────────────────────────────
|
||||
# Drawing-type-aware prompt builders
|
||||
# ──────────────────────────────────────────────────────────────────────────────
|
||||
@@ -426,8 +435,78 @@ class SymbolRecognitionAgent(BaseAgent):
|
||||
except Exception as p_err:
|
||||
logger.warning(f"Pathnovo Symbol Parser failed ({p_err}). Falling back to standard VLM pipeline.")
|
||||
|
||||
# Option B: VLM or GLM-OCR / RF-DETR object detector
|
||||
# Option B: Trained YOLOv8 Symbol Detector (custom best.pt from training pipeline)
|
||||
elif symbol_engine == "yolo_trained":
|
||||
weights_path = (
|
||||
state.get("yolo_weights_path")
|
||||
or os.getenv("DEFAULT_YOLO_WEIGHTS", "")
|
||||
)
|
||||
if not weights_path or not os.path.exists(weights_path):
|
||||
logger.warning(
|
||||
f"YOLOv8 weights not found at '{weights_path}'. "
|
||||
"Falling back to heuristic harvester. "
|
||||
"Run training first: python training/train.py yolo ..."
|
||||
)
|
||||
else:
|
||||
try:
|
||||
from ultralytics import YOLO
|
||||
from src.agents.base import BaseAgent as _BA
|
||||
|
||||
logger.info(f"SymbolRecognitionAgent: Loading trained YOLOv8 from '{weights_path}'...")
|
||||
yolo_model = YOLO(weights_path)
|
||||
|
||||
# Encode image for inference
|
||||
import numpy as np
|
||||
from PIL import Image as _PilImage
|
||||
with _PilImage.open(raw_image) as _img:
|
||||
img_w, img_h = _img.size
|
||||
_img_rgb = _img.convert("RGB")
|
||||
|
||||
results = yolo_model.predict(
|
||||
source=str(raw_image),
|
||||
conf=state.get("yolo_conf") or 0.25,
|
||||
iou=state.get("yolo_iou") or 0.45,
|
||||
imgsz=800, # Match training imgsz
|
||||
device="0" if _is_cuda_available() else "cpu",
|
||||
verbose=False,
|
||||
)
|
||||
|
||||
# YOLO class names from the training annotation_generator
|
||||
from training.annotation_generator import SYMBOL_CLASSES
|
||||
|
||||
for result in results:
|
||||
for box in result.boxes:
|
||||
cls_id = int(box.cls[0].item())
|
||||
conf_val = float(box.conf[0].item())
|
||||
# box.xyxyn → normalized [x1, y1, x2, y2]
|
||||
x1n, y1n, x2n, y2n = box.xyxyn[0].tolist()
|
||||
sym_type = SYMBOL_CLASSES[cls_id] if cls_id < len(SYMBOL_CLASSES) else "UNKNOWN"
|
||||
|
||||
symbols.append({
|
||||
"symbol_type" : sym_type,
|
||||
"inferred_tag": None,
|
||||
"ymin" : round(y1n, 4),
|
||||
"xmin" : round(x1n, 4),
|
||||
"ymax" : round(y2n, 4),
|
||||
"xmax" : round(x2n, 4),
|
||||
"confidence" : round(conf_val, 3),
|
||||
})
|
||||
|
||||
logger.info(
|
||||
f"SymbolRecognitionAgent (yolo_trained): detected {len(symbols)} symbols "
|
||||
f"from '{os.path.basename(weights_path)}'."
|
||||
)
|
||||
except ImportError:
|
||||
logger.error(
|
||||
"ultralytics not installed. Run: pip install ultralytics. "
|
||||
"Falling back to heuristic harvester."
|
||||
)
|
||||
except Exception as yolo_err:
|
||||
logger.error(f"Trained YOLOv8 inference failed ({yolo_err}). Falling back to heuristic harvester.")
|
||||
|
||||
# Option C: VLM or GLM-OCR / RF-DETR object detector
|
||||
elif not (local_mode or symbol_engine == "local"):
|
||||
|
||||
prompt = (
|
||||
f"You are an expert industrial vision detector specializing in ISA-5.1 and engineering symbol recognition for {dt_label} drawings.\n"
|
||||
f"Identify all graphical component symbols present in this drawing image.\n\n"
|
||||
|
||||
+97
-26
@@ -1,37 +1,77 @@
|
||||
import os
|
||||
import logging
|
||||
from typing import Optional
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
# API Keys
|
||||
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY", "")
|
||||
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")
|
||||
GROQ_API_KEY = os.getenv("GROQ_API_KEY", "")
|
||||
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY", "")
|
||||
QWEN_API_KEY = os.getenv("QWEN_API_KEY", os.getenv("OPENROUTER_API_KEY", os.getenv("DASHSCOPE_API_KEY", os.getenv("OPENAI_API_KEY", ""))))
|
||||
PATHNOVO_API_KEY = os.getenv("PATHNOVO_API_KEY", "")
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# API Endpoints
|
||||
QWEN_BASE_URL = os.getenv("QWEN_BASE_URL", "https://openrouter.ai/api/v1")
|
||||
OPENAI_BASE_URL = os.getenv("OPENAI_BASE_URL", "https://api.openai.com/v1")
|
||||
# ── API Keys ───────────────────────────────────────────────────────────────────
|
||||
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY", "")
|
||||
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")
|
||||
GROQ_API_KEY = os.getenv("GROQ_API_KEY", "")
|
||||
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY", "")
|
||||
QWEN_API_KEY = os.getenv("QWEN_API_KEY", os.getenv("OPENROUTER_API_KEY", os.getenv("DASHSCOPE_API_KEY", os.getenv("OPENAI_API_KEY", ""))))
|
||||
PATHNOVO_API_KEY = os.getenv("PATHNOVO_API_KEY", "")
|
||||
|
||||
# ── API Endpoints ──────────────────────────────────────────────────────────────
|
||||
QWEN_BASE_URL = os.getenv("QWEN_BASE_URL", "https://openrouter.ai/api/v1")
|
||||
OPENAI_BASE_URL = os.getenv("OPENAI_BASE_URL", "https://api.openai.com/v1")
|
||||
PATHNOVO_BASE_URL = os.getenv("PATHNOVO_BASE_URL", "https://api.pathnovo.com/v1/pid/extract")
|
||||
|
||||
# Model configurations
|
||||
GEMINI_MODEL = os.getenv("GEMINI_MODEL", "gemini-2.0-flash")
|
||||
OPENAI_MODEL = os.getenv("OPENAI_MODEL", "gpt-4o")
|
||||
GROQ_MODEL = os.getenv("GROQ_MODEL", "llama-3.3-70b-versatile")
|
||||
QWEN_MODEL = os.getenv("QWEN_MODEL", "qwen/qwen-2.5-72b-instruct")
|
||||
# ── Model Versions ─────────────────────────────────────────────────────────────
|
||||
# Gemini: upgraded to 2.5-flash (faster, higher context) with 2.5-pro available for accuracy
|
||||
GEMINI_MODEL = os.getenv("GEMINI_MODEL", "gemini-2.5-flash")
|
||||
GEMINI_PRO_MODEL = os.getenv("GEMINI_PRO_MODEL", "gemini-2.5-pro")
|
||||
OPENAI_MODEL = os.getenv("OPENAI_MODEL", "gpt-4o")
|
||||
GROQ_MODEL = os.getenv("GROQ_MODEL", "llama-3.3-70b-versatile")
|
||||
# Qwen: upgraded to qwen2.5-vl-72b-instruct for better vision understanding
|
||||
QWEN_MODEL = os.getenv("QWEN_MODEL", "qwen/qwen2.5-vl-72b-instruct")
|
||||
|
||||
# Default settings
|
||||
CHUNK_SIZE = int(os.getenv("CHUNK_SIZE", "1200"))
|
||||
# ── Text Chunking ──────────────────────────────────────────────────────────────
|
||||
CHUNK_SIZE = int(os.getenv("CHUNK_SIZE", "1200"))
|
||||
CHUNK_OVERLAP = int(os.getenv("CHUNK_OVERLAP", "250"))
|
||||
|
||||
# ── Per-Agent Token Budgets ────────────────────────────────────────────────────
|
||||
# TextRecognitionAgent needs high token budget for dense tag extraction
|
||||
TEXT_AGENT_MAX_TOKENS = int(os.getenv("TEXT_AGENT_MAX_TOKENS", "16384"))
|
||||
# SymbolRecognitionAgent: moderate budget for bounding-box structured output
|
||||
SYMBOL_AGENT_MAX_TOKENS = int(os.getenv("SYMBOL_AGENT_MAX_TOKENS", "8192"))
|
||||
# PipelineRecognitionAgent: moderate budget for relation/geometry lists
|
||||
PIPELINE_AGENT_MAX_TOKENS = int(os.getenv("PIPELINE_AGENT_MAX_TOKENS", "8192"))
|
||||
# CompilerAgent: highest budget — builds the full engineering graph
|
||||
COMPILER_MAX_TOKENS = int(os.getenv("COMPILER_MAX_TOKENS", "32768"))
|
||||
# Default fallback for all other agents
|
||||
DEFAULT_MAX_TOKENS = int(os.getenv("DEFAULT_MAX_TOKENS", "8192"))
|
||||
|
||||
def get_gemini_client(temperature: float = 0.0, model_name: Optional[str] = None):
|
||||
# ── Per-Agent Temperature Tuning ───────────────────────────────────────────────
|
||||
# Text extraction: deterministic (temperature=0.0) for consistent tag parsing
|
||||
TEXT_AGENT_TEMPERATURE = float(os.getenv("TEXT_AGENT_TEMPERATURE", "0.0"))
|
||||
# Symbol detection: slight randomness helps with ambiguous symbols
|
||||
SYMBOL_AGENT_TEMPERATURE = float(os.getenv("SYMBOL_AGENT_TEMPERATURE", "0.1"))
|
||||
# Pipeline/relation tracing: deterministic for consistent topology
|
||||
PIPELINE_AGENT_TEMPERATURE = float(os.getenv("PIPELINE_AGENT_TEMPERATURE", "0.0"))
|
||||
|
||||
# ── Retry & Backoff Policy ─────────────────────────────────────────────────────
|
||||
LLM_MAX_RETRIES = int(os.getenv("LLM_MAX_RETRIES", "5"))
|
||||
LLM_BASE_DELAY_SECONDS = float(os.getenv("LLM_BASE_DELAY_SECONDS", "2.0"))
|
||||
LLM_MAX_DELAY_SECONDS = float(os.getenv("LLM_MAX_DELAY_SECONDS", "60.0"))
|
||||
|
||||
# ── Pathnovo Enhanced Fallback Settings ───────────────────────────────────────
|
||||
PATHNOVO_TIMEOUT = int(os.getenv("PATHNOVO_TIMEOUT", "60"))
|
||||
PATHNOVO_MAX_RETRIES = int(os.getenv("PATHNOVO_MAX_RETRIES", "3"))
|
||||
|
||||
# ── Token Budget Warning Threshold (fraction of max_tokens) ───────────────────
|
||||
LLM_TOKEN_BUDGET_WARN_THRESHOLD = float(os.getenv("LLM_TOKEN_BUDGET_WARN_THRESHOLD", "0.85"))
|
||||
|
||||
|
||||
def get_gemini_client(temperature: float = 0.0, model_name: Optional[str] = None,
|
||||
max_tokens: Optional[int] = None):
|
||||
"""
|
||||
Initializes and returns the ChatGoogleGenerativeAI instance.
|
||||
Defaults to gemini-2.5-flash with configurable token budget.
|
||||
"""
|
||||
if not GEMINI_API_KEY:
|
||||
raise ValueError("GEMINI_API_KEY is not set in the environment or .env file.")
|
||||
@@ -42,7 +82,7 @@ def get_gemini_client(temperature: float = 0.0, model_name: Optional[str] = None
|
||||
model=model_name or GEMINI_MODEL,
|
||||
google_api_key=GEMINI_API_KEY,
|
||||
temperature=temperature,
|
||||
max_output_tokens=8192,
|
||||
max_output_tokens=max_tokens or DEFAULT_MAX_TOKENS,
|
||||
)
|
||||
|
||||
|
||||
@@ -52,12 +92,15 @@ def get_llm_client(
|
||||
api_key: Optional[str] = None,
|
||||
base_url: Optional[str] = None,
|
||||
temperature: float = 0.0,
|
||||
max_tokens: Optional[int] = None,
|
||||
):
|
||||
"""
|
||||
Universal factory for LLM clients supporting Gemini, OpenRouter (Qwen 2.5), OpenAI,
|
||||
Groq, or local endpoints (Ollama/vLLM).
|
||||
Universal factory for LLM clients supporting Gemini (2.5-flash / 2.5-pro),
|
||||
OpenRouter (Qwen2.5-VL-72B), OpenAI, Groq, Pathnovo, and local PaddleOCR fallback.
|
||||
Accepts per-agent max_tokens for fine-grained token budget control.
|
||||
"""
|
||||
prov = (provider or "gemini").lower()
|
||||
_max_tokens = max_tokens or DEFAULT_MAX_TOKENS
|
||||
|
||||
if prov == "gemini":
|
||||
key = api_key or GEMINI_API_KEY
|
||||
@@ -68,7 +111,21 @@ def get_llm_client(
|
||||
model=model_name or GEMINI_MODEL,
|
||||
google_api_key=key,
|
||||
temperature=temperature,
|
||||
max_output_tokens=8192,
|
||||
max_output_tokens=_max_tokens,
|
||||
)
|
||||
|
||||
elif prov == "gemini_pro":
|
||||
# High-accuracy path: use Gemini 2.5 Pro for complex structured extraction
|
||||
key = api_key or GEMINI_API_KEY
|
||||
if not key:
|
||||
raise ValueError("GEMINI_API_KEY is required for Gemini Pro provider.")
|
||||
from langchain_google_genai import ChatGoogleGenerativeAI
|
||||
logger.info(f"Using Gemini Pro model: {GEMINI_PRO_MODEL} (higher accuracy, slower).")
|
||||
return ChatGoogleGenerativeAI(
|
||||
model=model_name or GEMINI_PRO_MODEL,
|
||||
google_api_key=key,
|
||||
temperature=temperature,
|
||||
max_output_tokens=_max_tokens,
|
||||
)
|
||||
|
||||
elif prov in ("qwen", "openrouter", "openai_compatible", "openai"):
|
||||
@@ -92,10 +149,10 @@ def get_llm_client(
|
||||
openai_api_key=key,
|
||||
openai_api_base=endpoint,
|
||||
temperature=temperature,
|
||||
max_tokens=4096,
|
||||
max_tokens=_max_tokens,
|
||||
default_headers=headers,
|
||||
)
|
||||
|
||||
|
||||
elif prov == "groq":
|
||||
key = api_key or GROQ_API_KEY
|
||||
if not key:
|
||||
@@ -106,8 +163,22 @@ def get_llm_client(
|
||||
openai_api_key=key,
|
||||
openai_api_base="https://api.groq.com/openai/v1",
|
||||
temperature=temperature,
|
||||
max_tokens=_max_tokens,
|
||||
)
|
||||
|
||||
|
||||
elif prov in ("pathnovo", "pathnovo_api"):
|
||||
# Pathnovo is a REST API client, not an LLM — return None here;
|
||||
# agents handle Pathnovo via PathnovoAPIClient directly.
|
||||
logger.info("Provider 'pathnovo' selected. Agents will use PathnovoAPIClient directly.")
|
||||
return None
|
||||
|
||||
elif prov in ("paddle", "local", "paddle_ocr"):
|
||||
# PaddleOCR is a local OCR engine — return None here;
|
||||
# agents handle PaddleOCR via run_paddle_ocr() directly.
|
||||
logger.info("Provider 'paddle' selected. Agents will use PaddleOCR locally (zero API cost).")
|
||||
return None
|
||||
|
||||
else:
|
||||
# Fallback to Gemini
|
||||
return get_gemini_client(temperature=temperature, model_name=model_name)
|
||||
logger.warning(f"Unknown provider '{prov}'. Falling back to Gemini.")
|
||||
return get_gemini_client(temperature=temperature, model_name=model_name, max_tokens=_max_tokens)
|
||||
|
||||
+10
-1
@@ -66,7 +66,7 @@ class GraphState(TypedDict):
|
||||
# Selected Layer 2 Reasoning Engine choice ('rule_based', 'qwen', 'qwen_37', 'gemini', 'openai')
|
||||
reasoning_engine: Optional[str]
|
||||
|
||||
# Selected Symbol Recognition Engine choice ('vlm', 'glm_rfdetr', 'local')
|
||||
# Selected Symbol Recognition Engine choice ('vlm', 'glm_rfdetr', 'local', 'yolo_trained')
|
||||
symbol_engine: Optional[str]
|
||||
|
||||
# Selected Pipeline Recognition Engine choice ('cv_vlm_tracer', 'vlm_tracer', 'proximity_tracer')
|
||||
@@ -86,3 +86,12 @@ class GraphState(TypedDict):
|
||||
|
||||
# List of tags already sent for re-extraction to prevent infinite validation loops
|
||||
re_extracted_targets: List[str]
|
||||
|
||||
# Path to custom trained YOLOv8 weights (best.pt) for symbol detection
|
||||
# Set when symbol_engine='yolo_trained'. Falls back to DEFAULT_YOLO_WEIGHTS env var.
|
||||
yolo_weights_path: Optional[str]
|
||||
|
||||
# YOLOv8 inference thresholds (tunable from Streamlit sidebar)
|
||||
yolo_conf: Optional[float] # confidence threshold (default 0.25)
|
||||
yolo_iou: Optional[float] # NMS IoU threshold (default 0.45)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user