Watch
1
0
Fork
You've already forked Seyyed_arc
0
forked from hesabix/arc
Seyyed_arc/hesabixAPI/app/services/ai/ai_db_helpers.py

45 lines
1.4 KiB
Python
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
کمک‌کننده‌های session دیتابیس برای اجرای ابزارهای AI.
"""
from __future__ import annotations
import logging
from typing import Any, Dict
from sqlalchemy.orm import Session
from app.core.json_safe import json_dumps_safe, json_safe_value
logger = logging.getLogger(__name__)
__all__ = ["json_safe_value", "json_dumps_safe", "safe_db_rollback", "run_ai_registry_function"]
def safe_db_rollback(db: Session | None) -> None:
"""پاک‌سازی تراکنش abort‌شده بدون پرتاب خطای ثانویه."""
if db is None:
return
try:
db.rollback()
except Exception as exc:
logger.debug("safe_db_rollback ignored: %s", exc)
def run_ai_registry_function(
function_name: str,
arguments: Dict[str, Any],
context: Dict[str, Any],
) -> Any:
"""
اجرای function AI با session مستقل.
از اشتراک session استریم چت جلوگیری می‌کند تا خطای یک tool
بقیه را با InFailedSqlTransaction خراب نکند.
"""
from adapters.db.session import get_db_session
from app.services.ai.function_registry import registry
tool_context = {k: v for k, v in context.items() if k != "db"}
with get_db_session() as db:
tool_context["db"] = db
return registry.call_function(function_name, arguments, tool_context)