LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows
Python ai-agentsdata-engineeringdocument-aigenerative-aiidpjson-extractionllmmcp-serverocrpdf-extractionprompt-engineeringstructured-output
[FIX] Re connection for close db connection & Removing connection Pool (#685)
harini-venkataraman5a594da5ccb5
diff --git a/platform-service/sample.env b/platform-service/sample.envindex 666835055..0e533af8c 100644--- a/platform-service/sample.env+++ b/platform-service/sample.env@@ -26,10 +26,3 @@ FLIPT_SERVICE_AVAILABLE=FalseMODEL_PRICES_URL="https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json"MODEL_PRICES_TTL_IN_DAYS=7MODEL_PRICES_FILE_PATH="/tmp/model_prices.json"--#Connection Pool ENVs-POOL_MAX_CONNECTIONS=32-# Number of seconds to allow connections to be used. Same as gunicorn timeout-POOL_STALE_TIMEOUT=900-# Number of seconds to block when pool is full. Set to 5 minutes.-POOL_TIMEOUT=300diff --git a/platform-service/src/unstract/platform_service/controller/platform.py b/platform-service/src/unstract/platform_service/controller/platform.pyindex ad56a83b2..9d51243ce 100644--- a/platform-service/src/unstract/platform_service/controller/platform.py+++ b/platform-service/src/unstract/platform_service/controller/platform.py@@ -8,7 +8,7 @@ from cryptography.fernet import Fernet, InvalidTokenfrom flask import Blueprint, Requestfrom flask import current_app as appfrom flask import jsonify, make_response, request-from playhouse.pool import PooledPostgresqlDatabase+from peewee import PostgresqlDatabasefrom unstract.platform_service.constants import DBTable, DBTableV2, FeatureFlagfrom unstract.platform_service.env import Envfrom unstract.platform_service.exceptions import APIError@@ -20,19 +20,14 @@ from unstract.platform_service.helper.prompt_studio import PromptStudioRequestHefrom unstract.flags.feature_flag import check_feature_flag_status-be_db = PooledPostgresqlDatabase(+be_db = PostgresqlDatabase(Env.PG_BE_DATABASE,user=Env.PG_BE_USERNAME,password=Env.PG_BE_PASSWORD,host=Env.PG_BE_HOST,port=Env.PG_BE_PORT,- max_connections=Env.POOL_MAX_CONNECTIONS,- stale_timeout=Env.POOL_STALE_TIMEOUT,- timeout=Env.POOL_TIMEOUT,)be_db.init(Env.PG_BE_DATABASE)-be_db.connect()-platform_bp = Blueprint("platform", __name__)@@ -113,7 +108,6 @@ def validate_bearer_token(token: Optional[str]) -> bool:cursor = be_db.execute_sql(query)result_row = cursor.fetchone()cursor.close()- be_db.close()if not result_row or len(result_row) == 0:app.logger.error(f"Authentication failed. bearer token not found {token}")return Falsediff --git a/platform-service/src/unstract/platform_service/env.py b/platform-service/src/unstract/platform_service/env.pyindex f1a21c1f0..a938c4a44 100644--- a/platform-service/src/unstract/platform_service/env.py+++ b/platform-service/src/unstract/platform_service/env.py@@ -22,11 +22,6 @@ class Env:EnvManager.get_required_setting("MODEL_PRICES_TTL_IN_DAYS"))MODEL_PRICES_FILE_PATH = EnvManager.get_required_setting("MODEL_PRICES_FILE_PATH")- POOL_MAX_CONNECTIONS = int(- EnvManager.get_required_setting("POOL_MAX_CONNECTIONS", 32)- )- POOL_STALE_TIMEOUT = int(EnvManager.get_required_setting("POOL_STALE_TIMEOUT", 900))- POOL_TIMEOUT = int(EnvManager.get_required_setting("POOL_TIMEOUT", 300))EnvManager.raise_for_missing_envs()diff --git a/platform-service/src/unstract/platform_service/helper/adapter_instance.py b/platform-service/src/unstract/platform_service/helper/adapter_instance.pyindex 6667c1791..c0d03dbc1 100644--- a/platform-service/src/unstract/platform_service/helper/adapter_instance.py+++ b/platform-service/src/unstract/platform_service/helper/adapter_instance.py@@ -1,6 +1,6 @@from typing import Any, Optional-from playhouse.pool import PooledPostgresqlDatabase+from peewee import PostgresqlDatabasefrom unstract.platform_service.constants import DBTableV2, FeatureFlagfrom unstract.platform_service.exceptions import APIError@@ -10,7 +10,7 @@ from unstract.flags.feature_flag import check_feature_flag_statusclass AdapterInstanceRequestHelper:@staticmethoddef get_adapter_instance_from_db(- db_instance: PooledPostgresqlDatabase,+ db_instance: PostgresqlDatabase,organization_id: str,adapter_instance_id: str,organization_uid: Optional[int] = None,@@ -18,7 +18,7 @@ class AdapterInstanceRequestHelper:"""Get adapter instance from Backend Database.Args:- db_instance (PooledPostgresqlDatabase): Backend DB Connection Pool+ db_instance (PostgresqlDatabase): Backend DB Connectionorganization_id (str): organization schema idadapter_instance_id (str): adapter instance id@@ -45,5 +45,4 @@ class AdapterInstanceRequestHelper:columns = [desc[0] for desc in cursor.description]data_dict: dict[str, Any] = dict(zip(columns, result_row))cursor.close()- db_instance.close()return data_dictdiff --git a/platform-service/src/unstract/platform_service/helper/prompt_studio.py b/platform-service/src/unstract/platform_service/helper/prompt_studio.pyindex 276358f76..6801792c1 100644--- a/platform-service/src/unstract/platform_service/helper/prompt_studio.py+++ b/platform-service/src/unstract/platform_service/helper/prompt_studio.py@@ -1,6 +1,6 @@from typing import Any-from playhouse.pool import PooledPostgresqlDatabase+from peewee import PostgresqlDatabasefrom unstract.platform_service.constants import DBTableV2, FeatureFlagfrom unstract.platform_service.exceptions import APIError@@ -10,14 +10,14 @@ from unstract.flags.feature_flag import check_feature_flag_statusclass PromptStudioRequestHelper:@staticmethoddef get_prompt_instance_from_db(- db_instance: PooledPostgresqlDatabase,+ db_instance: PostgresqlDatabase,organization_id: str,prompt_registry_id: str,) -> dict[str, Any]:"""Get prompt studio registry from Backend Database.Args:- db_instance (PooledPostgresqlDatabase): Backend DB Connection Pool+ db_instance (PostgresqlDatabase): Backend DB Connectionorganization_id (str): organization schema idprompt_registry_id (str): prompt_registry_id@@ -45,5 +45,4 @@ class PromptStudioRequestHelper:columns = [desc[0] for desc in cursor.description]data_dict: dict[str, Any] = dict(zip(columns, result_row))cursor.close()- db_instance.close()return data_dictdiff --git a/platform-service/src/unstract/platform_service/run.py b/platform-service/src/unstract/platform_service/run.pyindex ed81aff97..ae7f9e1a4 100644--- a/platform-service/src/unstract/platform_service/run.py+++ b/platform-service/src/unstract/platform_service/run.py@@ -3,6 +3,7 @@ from logging.config import dictConfigfrom dotenv import load_dotenvfrom flask import Flaskfrom unstract.platform_service.controller import api+from unstract.platform_service.controller.platform import be_dbload_dotenv()@@ -35,6 +36,13 @@ def create_app() -> Flask:app = create_app()+[email protected]_request+def before_request() -> None:+ if be_db.is_closed():+ be_db.connect(reuse_if_open=True)++if __name__ == "__main__":# Start the serverapp.run(host="0.0.0.0", port=3001, load_dotenv=True)diff --git a/prompt-service/sample.env b/prompt-service/sample.envindex 752394286..53f27dad2 100644--- a/prompt-service/sample.env+++ b/prompt-service/sample.env@@ -27,10 +27,3 @@ EVALUATION_SERVER_PORT=9000PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python# Flipt ServiceFLIPT_SERVICE_AVAILABLE=False--#Connection Pool ENVs-POOL_MAX_CONNECTIONS=32-# Number of seconds to allow connections to be used. Same as gunicorn timeout-POOL_STALE_TIMEOUT=900-# Number of seconds to block when pool is full. Set to 5 minutes.-POOL_TIMEOUT=300diff --git a/prompt-service/src/unstract/prompt_service/authentication_middleware.py b/prompt-service/src/unstract/prompt_service/authentication_middleware.pyindex 530114ab9..fbf03c37b 100644--- a/prompt-service/src/unstract/prompt_service/authentication_middleware.py+++ b/prompt-service/src/unstract/prompt_service/authentication_middleware.py@@ -25,7 +25,6 @@ class AuthenticationMiddleware:cursor = db.execute_sql(query)result_row = cursor.fetchone()cursor.close()- db.close()if not result_row or len(result_row) == 0:current_app.logger.error(f"Authentication failed. bearer token not found {token}"diff --git a/prompt-service/src/unstract/prompt_service/config.py b/prompt-service/src/unstract/prompt_service/config.pyindex e61f8138b..5d6a2ef15 100644--- a/prompt-service/src/unstract/prompt_service/config.py+++ b/prompt-service/src/unstract/prompt_service/config.py@@ -4,7 +4,7 @@ from os import environ as envfrom dotenv import load_dotenvfrom flask import Flask-from playhouse.pool import PooledPostgresqlDatabase+from peewee import PostgresqlDatabasefrom unstract.prompt_service.constants import LogLevelload_dotenv()@@ -28,7 +28,7 @@ dictConfig(})-db = PooledPostgresqlDatabase(None)+db = PostgresqlDatabase(None)def get_env_or_die(env_key: str) -> str:@@ -54,9 +54,6 @@ def create_app() -> Flask:db_user = get_env_or_die("PG_BE_USERNAME")db_pass = get_env_or_die("PG_BE_PASSWORD")db_name = get_env_or_die("PG_BE_DATABASE")- max_connections = int(get_env_or_die("POOL_MAX_CONNECTIONS"))- stale_timeout = int(get_env_or_die("POOL_STALE_TIMEOUT"))- timeout = int(get_env_or_die("POOL_TIMEOUT"))# Initialize and connect to the databasedb.init(@@ -65,10 +62,5 @@ def create_app() -> Flask:password=db_pass,host=db_host,port=db_port,- max_connections=max_connections,- stale_timeout=stale_timeout,- timeout=timeout,)- db.connect()-return appdiff --git a/prompt-service/src/unstract/prompt_service/main.py b/prompt-service/src/unstract/prompt_service/main.pyindex d80d53781..b92fb0076 100644--- a/prompt-service/src/unstract/prompt_service/main.py+++ b/prompt-service/src/unstract/prompt_service/main.py@@ -7,7 +7,7 @@ from typing import Any, Optionalfrom flask import json, jsonify, requestfrom llama_index.core.vector_stores import ExactMatchFilter, MetadataFiltersfrom unstract.prompt_service.authentication_middleware import AuthenticationMiddleware-from unstract.prompt_service.config import create_app+from unstract.prompt_service.config import create_app, dbfrom unstract.prompt_service.constants import PromptServiceContants as PSKeysfrom unstract.prompt_service.constants import RunLevelfrom unstract.prompt_service.exceptions import APIError, ErrorResponse, NoPayloadError@@ -48,6 +48,12 @@ app = create_app()plugin_loader(app)[email protected]_request+def before_request() -> None:+ if db.is_closed():+ db.connect(reuse_if_open=True)++def _publish_log(log_events_id: str,component: dict[str, str],