quick-pp 0.2.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. quick_pp/__init__.py +0 -0
  2. quick_pp/api/__init__.py +0 -0
  3. quick_pp/api/exceptions.py +61 -0
  4. quick_pp/api/fastapi_mlflow/__init__.py +1 -0
  5. quick_pp/api/fastapi_mlflow/_mlflow_types.py +59 -0
  6. quick_pp/api/fastapi_mlflow/applications.py +72 -0
  7. quick_pp/api/fastapi_mlflow/exceptions.py +22 -0
  8. quick_pp/api/fastapi_mlflow/predictors.py +96 -0
  9. quick_pp/api/main.py +90 -0
  10. quick_pp/api/mlflow_model_deployment.py +99 -0
  11. quick_pp/api/qpp_assistant.py +160 -0
  12. quick_pp/api/router.py +18 -0
  13. quick_pp/api/schemas/lithology_hc_correction.py +39 -0
  14. quick_pp/api/schemas/lithology_ssc.py +37 -0
  15. quick_pp/api/schemas/lithology_vsh_gr.py +25 -0
  16. quick_pp/api/schemas/permeability_choo.py +25 -0
  17. quick_pp/api/schemas/permeability_others.py +24 -0
  18. quick_pp/api/schemas/porosity.py +22 -0
  19. quick_pp/api/schemas/ressum.py +29 -0
  20. quick_pp/api/schemas/saturation_archie.py +25 -0
  21. quick_pp/api/schemas/saturation_b.py +24 -0
  22. quick_pp/api/schemas/saturation_qv.py +26 -0
  23. quick_pp/api/schemas/saturation_rw.py +24 -0
  24. quick_pp/api/schemas/saturation_temp_grad.py +24 -0
  25. quick_pp/api/schemas/saturation_waxman_smits.py +28 -0
  26. quick_pp/api/services/las_handler.py +136 -0
  27. quick_pp/api/services/lithology.py +278 -0
  28. quick_pp/api/services/permeability.py +252 -0
  29. quick_pp/api/services/porosity.py +151 -0
  30. quick_pp/api/services/reservoir_summary.py +78 -0
  31. quick_pp/api/services/saturation.py +359 -0
  32. quick_pp/api/static/favicon.ico +0 -0
  33. quick_pp/api/static/logo.png +0 -0
  34. quick_pp/cli.py +118 -0
  35. quick_pp/config.py +94 -0
  36. quick_pp/core_calibration.py +394 -0
  37. quick_pp/fluid_type.py +128 -0
  38. quick_pp/geomechanics.py +195 -0
  39. quick_pp/las_handler.py +327 -0
  40. quick_pp/lithology/__init__.py +80 -0
  41. quick_pp/lithology/carbonate.py +166 -0
  42. quick_pp/lithology/multi_mineral.py +151 -0
  43. quick_pp/lithology/sand_shale.py +79 -0
  44. quick_pp/lithology/sand_silt_clay.py +131 -0
  45. quick_pp/logger.py +19 -0
  46. quick_pp/modelling/__init__.py +0 -0
  47. quick_pp/modelling/config.py +72 -0
  48. quick_pp/modelling/mock_data/mock_data.parquet +0 -0
  49. quick_pp/modelling/predict_pipeline.py +126 -0
  50. quick_pp/modelling/train_pipeline.py +220 -0
  51. quick_pp/modelling/utils.py +111 -0
  52. quick_pp/objects.py +177 -0
  53. quick_pp/permeability.py +151 -0
  54. quick_pp/plotter/__init__.py +0 -0
  55. quick_pp/plotter/plotter.py +315 -0
  56. quick_pp/plotter/well_log.py +187 -0
  57. quick_pp/plotter/well_log_config.py +409 -0
  58. quick_pp/porosity.py +341 -0
  59. quick_pp/qaqc.py +436 -0
  60. quick_pp/ressum.py +326 -0
  61. quick_pp/rock_type.py +499 -0
  62. quick_pp/saturation.py +455 -0
  63. quick_pp/utils.py +328 -0
  64. quick_pp-0.2.3.dist-info/METADATA +103 -0
  65. quick_pp-0.2.3.dist-info/RECORD +69 -0
  66. quick_pp-0.2.3.dist-info/WHEEL +4 -0
  67. quick_pp-0.2.3.dist-info/entry_points.txt +2 -0
  68. quick_pp-0.2.3.dist-info/licenses/AUTHORS.rst +13 -0
  69. quick_pp-0.2.3.dist-info/licenses/LICENSE +22 -0
quick_pp/__init__.py ADDED
File without changes
File without changes
@@ -0,0 +1,61 @@
1
+ """Exception definition"""
2
+ from sqlalchemy.exc import IntegrityError
3
+ from psycopg2.errors import UniqueViolation
4
+
5
+
6
+ class BadRequestException(Exception):
7
+ """
8
+ This exception could be raise when receiving unexpected input from user
9
+ """
10
+ def __init__(self, name: str) -> None:
11
+ self.name = name
12
+
13
+
14
+ class DataNotFoundException(Exception):
15
+ """
16
+ This exception could be raise when receiving unexpected input from user
17
+ """
18
+ def __init__(self, name: str) -> None:
19
+ self.name = name
20
+
21
+
22
+ class MethodNotAllowedException(Exception):
23
+ """
24
+ This exception could be raise when receiving unexpected input from user
25
+ """
26
+ def __init__(self, name: str) -> None:
27
+ self.name = name
28
+
29
+
30
+ class NotAuthorizedException(Exception):
31
+ """
32
+ This exception could be raise when receiving unexpected input from user
33
+ """
34
+ def __init__(self, name: str) -> None:
35
+ self.name = name
36
+
37
+
38
+ class UnknownException(Exception):
39
+ """
40
+ This exception could be raise when receiving unexpected input from user
41
+ """
42
+ def __init__(self, name: str) -> None:
43
+ self.name = name
44
+
45
+
46
+ def return_exception_message(exc: Exception) -> str:
47
+ if isinstance(exc, DataNotFoundException):
48
+ return "Not Found!"
49
+ if isinstance(exc, NotAuthorizedException):
50
+ return "Not Authorized!"
51
+ if isinstance(exc, BadRequestException):
52
+ return "Bad request!"
53
+ if isinstance(exc, UnknownException):
54
+ return "Unrecognized error!"
55
+ return "Oops! Something was wrong"
56
+
57
+
58
+ def return_database_integrity_error_message(exc: IntegrityError) -> str:
59
+ if isinstance(exc.orig, UniqueViolation):
60
+ return "Unique Violation! Data input already exists"
61
+ return "Oops! Data Inegrity Error, please check the input data"
@@ -0,0 +1 @@
1
+ __version__ = "0.1.2"
@@ -0,0 +1,59 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Mapping from mlflow schemas to Pydantic models and native Python types.
3
+
4
+ Copyright (C) 2022, Auto Trader UK
5
+
6
+ """
7
+
8
+ from datetime import date, datetime
9
+ from typing import Dict, Optional, Union
10
+
11
+ MLFLOW_SIGNATURE_TO_PYTHON_TYPE_MAP = {
12
+ "boolean": bool,
13
+ "integer": int,
14
+ "long": int,
15
+ "int32": int,
16
+ "int64": int,
17
+ "double": float,
18
+ "float": float,
19
+ "float32": float,
20
+ "float64": float,
21
+ "string": str,
22
+ "str": str,
23
+ "object": str,
24
+ "binary": bytes,
25
+ "datetime": Union[datetime, date],
26
+ }
27
+
28
+
29
+ class UnsupportedFieldTypeError(Exception):
30
+ pass
31
+
32
+
33
+ def get_field(type_name: str, nullable: bool):
34
+ """
35
+ :param nullable (bool): Should field be nullable
36
+ """
37
+ try:
38
+ type_ = MLFLOW_SIGNATURE_TO_PYTHON_TYPE_MAP[type_name]
39
+ except KeyError:
40
+ raise UnsupportedFieldTypeError(f"Field type not supported: {type_name}")
41
+
42
+ if nullable:
43
+ type_ = Optional[type_]
44
+
45
+ field = (type_, ...) # Ellipsis (...) because default value is unknown
46
+ return field
47
+
48
+
49
+ def build_model_fields(schema, nullable: bool = False) -> Dict:
50
+ """Return a dict mapping field names -> (type, default).
51
+
52
+ :param nullable (bool): Should fields be nullable
53
+ """
54
+ if schema.has_input_names():
55
+ return {
56
+ item["name"]: get_field(item["type"], nullable) for item in schema.to_dict()
57
+ }
58
+ else:
59
+ return {"prediction": get_field(schema.numpy_types()[0].name, nullable)}
@@ -0,0 +1,72 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Build FastAPI applications for mlflow model predictions.
3
+
4
+ Copyright (C) 2022, Auto Trader UK
5
+
6
+ """
7
+
8
+ import logging
9
+ from inspect import signature
10
+
11
+ from fastapi import FastAPI, Request
12
+ from fastapi.responses import ORJSONResponse
13
+ from mlflow.pyfunc import PyFuncModel # type: ignore
14
+
15
+ from quick_pp.api.fastapi_mlflow.exceptions import DictSerialisableException
16
+ from quick_pp.api.fastapi_mlflow.predictors import build_predictor
17
+
18
+
19
+ def build_app(app, pyfunc_model: PyFuncModel, route: str) -> FastAPI:
20
+ """Build and return a FastAPI app for the mlflow model."""
21
+ logger = logging.getLogger(__name__)
22
+ predictor = build_predictor(pyfunc_model)
23
+ response_model = signature(predictor).return_annotation
24
+
25
+ # Get input and output schemas from the model metadata
26
+ input_schema = pyfunc_model.metadata.get_input_schema()
27
+ input_features = [item['name'] for item in input_schema.to_dict()]
28
+ output_schema = pyfunc_model.metadata.get_output_schema()
29
+ target_features = [item['name'] for item in output_schema.to_dict()]
30
+
31
+ model_name = route.removeprefix('/')
32
+ input_example = ', '.join([f'\"{f}\": <value>' for f in input_features])
33
+ output_example = ', '.join([f'\"{f}\": <predicted_value>' for f in target_features])
34
+ app.add_api_route(
35
+ f"{route}",
36
+ predictor,
37
+ response_model=response_model,
38
+ response_class=ORJSONResponse,
39
+ methods=["POST"],
40
+ description=(
41
+ f"Predict using the '{model_name}' MLflow model.\n\n"
42
+ f"**Input:**\n"
43
+ f"- Request body must be a JSON object with the following features as keys:\n"
44
+ f" {', '.join(input_features)}\n"
45
+ f"- Example: {{ {input_example} }}\n\n"
46
+ f"**Output:**\n"
47
+ f"- JSON object with the following keys: {', '.join(target_features)}\n"
48
+ f"- Example: {{ {output_example} }}\n"
49
+ ),
50
+ operation_id=f"predict_{model_name}",
51
+ )
52
+
53
+ @app.exception_handler(DictSerialisableException)
54
+ def handle_serialisable_exception(
55
+ req: Request, exc: DictSerialisableException
56
+ ) -> ORJSONResponse:
57
+ nonlocal logger
58
+ req_id = req.headers.get("x-request-id")
59
+ extra = {"x-request-id": req_id} if req_id is not None else {}
60
+ logger.exception(exc.message, extra=extra)
61
+ return ORJSONResponse(
62
+ status_code=500,
63
+ content=exc.to_dict(),
64
+ )
65
+
66
+ @app.exception_handler(Exception)
67
+ def handle_exception(req: Request, exc: Exception) -> ORJSONResponse:
68
+ return handle_serialisable_exception(
69
+ req, DictSerialisableException.from_exception(exc)
70
+ )
71
+
72
+ return app
@@ -0,0 +1,22 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Exceptions.
3
+
4
+ Copyright (C) 2023, Auto Trader UK
5
+ Created 17. Apr 2023
6
+
7
+ """
8
+
9
+
10
+ class DictSerialisableException(Exception):
11
+ """An Exception wrapper for formatting."""
12
+
13
+ def __init__(self, name: str, message: str):
14
+ self.name = name
15
+ self.message = message
16
+
17
+ @classmethod
18
+ def from_exception(cls, exc: Exception):
19
+ return cls(name=exc.__class__.__name__, message=str(exc))
20
+
21
+ def to_dict(self):
22
+ return {"name": self.name, "message": self.message}
@@ -0,0 +1,96 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Build functions to wrap mlflow models.
3
+
4
+ Existing implementation returns a synchronous/blocking function. This decision
5
+ was taken because applying ML models is probably CPU-bound. Not having
6
+ unnecessary asynchronous code also makes testing simpler.
7
+
8
+ Current supports only the pyfunc flavour.
9
+
10
+ Copyright (C) 2022, Auto Trader UK
11
+
12
+ """
13
+
14
+ from typing import Any, Callable, Dict, List, no_type_check
15
+
16
+ import numpy as np
17
+ import pandas as pd
18
+ from mlflow.pyfunc import PyFuncModel # type: ignore
19
+ from pydantic import BaseModel, create_model
20
+
21
+ from quick_pp.api.fastapi_mlflow._mlflow_types import (
22
+ MLFLOW_SIGNATURE_TO_PYTHON_TYPE_MAP,
23
+ build_model_fields,
24
+ )
25
+ from quick_pp.api.fastapi_mlflow.exceptions import DictSerialisableException
26
+
27
+
28
+ @no_type_check # Some types here are too dynamic for type checking
29
+ def build_predictor(model: PyFuncModel) -> Callable[[BaseModel], Any]:
30
+ """Build and return a function that wraps the mlflow model.
31
+
32
+ Currently supports only the `pyfunc`_ flavour of mlflow.
33
+
34
+ :param model: PyFuncModel
35
+ :return: Function suitable for mounting as a FastAPI endpoint or route.
36
+
37
+ Example::
38
+
39
+ model = load_model("/Users/me/path/to/local/model")
40
+ predictor = build_predictor(model)
41
+
42
+ .. _pyfunc: https://www.mlflow.org/docs/latest/python_api/mlflow.pyfunc.html
43
+
44
+ """
45
+ input_schema = model.metadata.get_input_schema()
46
+ input_model = create_model("RequestRow", **(build_model_fields(input_schema)))
47
+ output_schema = model.metadata.get_output_schema()
48
+ output_features = [item['name'] for item in output_schema.to_dict()]
49
+ output_model = create_model("ResponseRow", **(build_model_fields(output_schema, nullable=True)))
50
+
51
+ class Request(BaseModel):
52
+ data: List[input_model]
53
+
54
+ class Response(BaseModel):
55
+ data: List[output_model]
56
+
57
+ async def request_to_dataframe(request: Request) -> pd.DataFrame:
58
+ df = pd.DataFrame([row.model_dump() for row in request.data], dtype=object)
59
+ for item in input_schema.to_dict():
60
+ if item["type"] in ("integer", "int32"):
61
+ df[item["name"]] = df[item["name"]].astype(np.int32)
62
+ elif item["type"] == "datetime":
63
+ df[item["name"]] = pd.to_datetime(df[item["name"]], utc=True)
64
+ else:
65
+ df[item["name"]] = df[item["name"]].astype(
66
+ MLFLOW_SIGNATURE_TO_PYTHON_TYPE_MAP.get(item["type"], object)
67
+ )
68
+
69
+ return df
70
+
71
+ async def predictor(request: Request) -> Response:
72
+ try:
73
+ predictions = model.predict(await request_to_dataframe(request))
74
+ response_data = await convert_predictions_to_python(predictions, output_features)
75
+ return Response(data=response_data)
76
+ except Exception as exc:
77
+ raise DictSerialisableException.from_exception(exc) from exc
78
+
79
+ return predictor # type: ignore
80
+
81
+
82
+ async def convert_predictions_to_python(results, output_features) -> List[Dict[str, Any]]:
83
+ """Convert and return predictions in native Python types."""
84
+ try:
85
+ results = pd.DataFrame(results, columns=output_features)
86
+ response_data = (
87
+ results.fillna(np.nan).replace([np.nan], [None]).to_dict(orient="records")
88
+ )
89
+ except (AttributeError, TypeError):
90
+ # Return type is probably a simple array-like
91
+ # Replace NaN with None
92
+ response_data = []
93
+ for row in results:
94
+ value = row if not pd.isnull(row) else None
95
+ response_data.append({"prediction": value})
96
+ return response_data
quick_pp/api/main.py ADDED
@@ -0,0 +1,90 @@
1
+ from fastapi import FastAPI
2
+ from fastapi.responses import JSONResponse
3
+ from fastapi.middleware.cors import CORSMiddleware
4
+ from fastapi.staticfiles import StaticFiles
5
+ from fastapi.responses import FileResponse
6
+ from .exceptions import return_exception_message
7
+ from fastapi_mcp import FastApiMCP
8
+ from chainlit.utils import mount_chainlit
9
+
10
+ from .router import api_router
11
+
12
+ tags_metadata = [
13
+ {
14
+ "name": "File Handler",
15
+ "description": "File handler related endpoints."
16
+ },
17
+ {
18
+ "name": "Lithology",
19
+ "description": "Lithology related endpoints."
20
+ },
21
+ {
22
+ "name": "Porosity",
23
+ "description": "Porosity related endpoints."
24
+ },
25
+ {
26
+ "name": "Saturation",
27
+ "description": "Saturation related endpoints."
28
+ },
29
+ {
30
+ "name": "Permeability",
31
+ "description": "Permeability related endpoints."
32
+ },
33
+ {
34
+ "name": "Reservoir Summary",
35
+ "description": "Reservoir summary related endpoints."
36
+ }
37
+ ]
38
+
39
+ app = FastAPI(
40
+ title="quick_pp API",
41
+ description="API for quick_pp library.",
42
+ contact={"name": "Imran Fadhil",
43
+ "url": "https://github.com/imranfadhil/quick_pp", "email": "imranfadhil@gmail.com"},
44
+ swagger_ui_parameters={"defaultModelsExpandDepth": -1},
45
+ openapi_tags=tags_metadata,
46
+ debug=True
47
+ )
48
+ app.mount("/static", StaticFiles(directory=r"quick_pp/api/static"), name="static")
49
+ app.include_router(api_router)
50
+
51
+
52
+ @app.get("/favicon.ico", include_in_schema=False)
53
+ async def favicon():
54
+ return FileResponse("static/favicon.ico")
55
+
56
+ origins = ["*"]
57
+ app.add_middleware(
58
+ CORSMiddleware,
59
+ allow_origins=origins,
60
+ allow_credentials=True,
61
+ allow_methods=origins,
62
+ allow_headers=origins,
63
+ )
64
+
65
+
66
+ @app.get("/", include_in_schema=False)
67
+ async def root():
68
+ return {"message": "Welcome to quick_pp API. Please refer to the documentation at /docs or /redoc. "
69
+ "You can also use the chat assistant at /qpp_assistant."}
70
+
71
+
72
+ @app.exception_handler(Exception)
73
+ async def internal_server_exception_handler(exc: Exception):
74
+ return JSONResponse(
75
+ status_code=500,
76
+ content={
77
+ "message": return_exception_message(exc),
78
+ "detail": f"{repr(exc)}"
79
+ }
80
+ )
81
+
82
+ mcp = FastApiMCP(
83
+ app,
84
+ name="quick_pp API MCP",
85
+ describe_all_responses=True, # Include all possible response schemas
86
+ describe_full_response_schema=True # Include full JSON schema in descriptions
87
+ )
88
+ mcp.mount()
89
+
90
+ mount_chainlit(app=app, target=r"quick_pp\api\qpp_assistant.py", path="/qpp_assistant")
@@ -0,0 +1,99 @@
1
+ from fastapi import FastAPI, Request
2
+ from fastapi_mcp import FastApiMCP
3
+ from fastapi.middleware.cors import CORSMiddleware
4
+ from fastapi.staticfiles import StaticFiles
5
+ from fastapi.responses import FileResponse
6
+ from starlette.types import Message
7
+ from datetime import datetime
8
+ import mlflow
9
+ from mlflow.pyfunc import load_model
10
+ import mlflow.tracking as mlflow_tracking
11
+
12
+ # # Uncomment below 3 lines to run >> if __name__ == "__main__"
13
+ # import os
14
+ # import sys
15
+ # sys.path.append(os.getcwd())
16
+
17
+ from quick_pp.api.fastapi_mlflow.applications import build_app
18
+ from quick_pp.modelling.utils import get_model_info, run_mlflow_server
19
+ from quick_pp.logger import logger
20
+
21
+
22
+ app = FastAPI(
23
+ title='quick_pp - ML Models',
24
+ description="API for quick_pp library.",
25
+ contact={"name": "Imran Fadhil",
26
+ "url": "https://github.com/imranfadhil/quick_pp", "email": "imranfadhil@gmail.com"},
27
+ swagger_ui_parameters={"defaultModelsExpandDepth": -1},
28
+ debug=True)
29
+ app.mount("/static", StaticFiles(directory=r"quick_pp/api/static"), name="static")
30
+
31
+
32
+ @app.get("/favicon.ico", include_in_schema=False)
33
+ async def favicon():
34
+ return FileResponse("static/favicon.ico")
35
+
36
+
37
+ # set_body and get_body required to extract request body in middleware
38
+ async def set_body(request: Request, body: bytes):
39
+ async def receive() -> Message:
40
+ return {"type": "http.request", "body": body}
41
+ request._receive = receive
42
+
43
+
44
+ async def get_body(request: Request) -> bytes:
45
+ body = await request.body()
46
+ await set_body(request, body)
47
+ return body
48
+
49
+ # Run MLflow server
50
+ run_mlflow_server('local')
51
+
52
+ client = mlflow_tracking.MlflowClient()
53
+
54
+ start_time = datetime.now()
55
+ model_count = 0
56
+ logger.info(f"Tracking uri {mlflow.get_tracking_uri()}")
57
+
58
+ try:
59
+ # Get latest registered models
60
+ for rm in client.search_registered_models():
61
+ model_info = get_model_info(rm.latest_versions)
62
+ if 'reg_model_name' in model_info.keys():
63
+ model_uri = f"models:/{model_info['reg_model_name']}/{model_info['version']}"
64
+ logger.info(f"Loading model: {model_uri}")
65
+ model = load_model(model_uri)
66
+
67
+ model_count += 1
68
+ # Build API for the loaded model
69
+ route = fr"/{model_info['reg_model_name']}"
70
+ app = build_app(app, model, route)
71
+ logger.info(f"Mounted model #{model_count} at route: {route}")
72
+
73
+ # Set up CORS middleware
74
+ origins = ["*"]
75
+ app.add_middleware(
76
+ CORSMiddleware,
77
+ allow_origins=origins,
78
+ allow_credentials=True,
79
+ allow_methods=origins,
80
+ allow_headers=origins,
81
+ )
82
+
83
+ # Mount the model using FastApiMCP
84
+ mcp = FastApiMCP(app)
85
+ mcp.mount()
86
+ logger.info("FastApiMCP mounted successfully.")
87
+
88
+ except Exception as e:
89
+ logger.error(f"Mounting #{model_count} | {model_info.get('reg_model_name', 'unknown')}/"
90
+ f"{model_info.get('version', 'unknown')} - Error: {e}")
91
+
92
+ duration = round((datetime.now() - start_time).total_seconds() / 60, 3)
93
+ logger.info(f"Completed mounting {model_count} models in {duration} minutes")
94
+
95
+
96
+ if __name__ == '__main__':
97
+ import uvicorn
98
+
99
+ uvicorn.run("quick_pp.api.mlflow_model_deployment:app", host='0.0.0.0', port=5555, reload=False)
@@ -0,0 +1,160 @@
1
+ from mcp import ClientSession
2
+ import chainlit as cl
3
+ from langchain_core.prompts import ChatPromptTemplate
4
+ from langchain_ollama.chat_models import ChatOllama
5
+ import re
6
+ import json
7
+
8
+
9
+ @cl.on_mcp_connect
10
+ async def on_mcp(connection, session: ClientSession):
11
+ # List available tools
12
+ result = await session.list_tools()
13
+
14
+ # Process tool metadata
15
+ tools = [{
16
+ "name": t.name,
17
+ "description": t.description,
18
+ "input_schema": t.inputSchema,
19
+ } for t in result.tools]
20
+
21
+ # Store tools for later use
22
+ mcp_tools = cl.user_session.get("mcp_tools", {})
23
+ mcp_tools[connection.name] = tools
24
+ cl.user_session.set("mcp_tools", mcp_tools)
25
+
26
+
27
+ @cl.step(type="tool")
28
+ async def call_tool(tool_use):
29
+ tool_name = tool_use["name"]
30
+ tool_input = tool_use["input"]
31
+
32
+ current_step = cl.context.current_step
33
+ current_step.name = tool_name
34
+
35
+ # Identify which mcp is used
36
+ mcp_tools = cl.user_session.get("mcp_tools", {})
37
+ mcp_name = None
38
+
39
+ for connection_name, tools in mcp_tools.items():
40
+ if any(tool.get("name") == tool_name for tool in tools):
41
+ mcp_name = connection_name
42
+ break
43
+
44
+ if not mcp_name:
45
+ current_step.output = json.dumps({"error": f"Tool {tool_name} not found in any MCP connection"})
46
+ return current_step.output
47
+
48
+ mcp_session, _ = cl.context.session.mcp_sessions.get(mcp_name)
49
+
50
+ if not mcp_session:
51
+ current_step.output = json.dumps({"error": f"MCP {mcp_name} not found in any MCP connection"})
52
+ return current_step.output
53
+
54
+ try:
55
+ current_step.output = await mcp_session.call_tool(tool_name, tool_input)
56
+ except Exception as e:
57
+ current_step.output = json.dumps({"error": str(e)})
58
+
59
+ return current_step.output
60
+
61
+
62
+ async def call_ollama(messages):
63
+
64
+ # Prepare tool descriptions for the prompt
65
+ mcp_tools = cl.user_session.get("mcp_tools", {})
66
+ tool_names = ", ".join(
67
+ tool['name']
68
+ for tool_list in mcp_tools.values() for tool in tool_list
69
+ )
70
+ tool_names = tool_names.replace('{', '{{').replace('}', '}}')
71
+ tool_descriptions = "\n".join(
72
+ f"- {tool['name']}: {tool['description']}"
73
+ for tool_list in mcp_tools.values() for tool in tool_list
74
+ )
75
+ tool_descriptions = tool_descriptions.replace('{', '{{').replace('}', '}}')
76
+
77
+ # Create the prompt template with tools info
78
+ prompt = ChatPromptTemplate.from_messages([
79
+ ("system", f'''
80
+ You are a Petrophysics specialist and you need to answer accurately and efficiently.
81
+ You can call tools to answer user questions.
82
+ You can use the following tools: {tool_names}.
83
+ Here are the tools' descriptions: {tool_descriptions}.
84
+ When a user asks a question, select the single best tool to answer it (if any).
85
+ If a tool is relevant, respond ONLY in the following JSON format:
86
+ {{{{"tool_call": {{{{"name": "<tool_name>", "input": {{{{<input_parameters>}}}}}}}}}}}}
87
+ If no tool is relevant, answer the question directly in natural language.
88
+ Do not explain your reasoning. Do not output anything except the JSON or the direct answer.
89
+ If you need more information from the user to use a tool, ask for it directly.
90
+ Example: If the user asks 'Calculate porosity for well X', and there is a 'calculate_porosity' tool, respond with:
91
+ {{{{"tool_call": {{{{"name": "calculate_porosity", "input": {{{{"well_id": "X"}}}}}}}}}}}}
92
+ '''),
93
+ ("user", "Please answer the question and use the tools if needed."),
94
+ ("user", "{input}")
95
+ ])
96
+
97
+ llm = ChatOllama(model='qwen3', num_ctx=16384, temperature=0.9)
98
+ chain = prompt | llm
99
+ user_input = messages[-1]["content"] if messages else ""
100
+ response = chain.invoke({
101
+ "input": user_input,
102
+ })
103
+ # Remove all substrings bounded by <think>...</think>
104
+ if isinstance(response.content, str):
105
+ response.content = re.sub(r"<think>(.|\n)*?</think>", "", response.content, flags=re.DOTALL)
106
+
107
+ return response
108
+
109
+
110
+ @cl.on_chat_start
111
+ async def start_chat():
112
+ cl.user_session.set("chat_messages", [])
113
+
114
+
115
+ @cl.on_message
116
+ async def on_message(msg: cl.Message):
117
+ chat_messages = cl.user_session.get("chat_messages")
118
+ chat_messages.append({"role": "user", "content": msg.content})
119
+ response = await call_ollama(chat_messages)
120
+
121
+ if "tool_call" in response.content:
122
+ # Ensure response.content is a string and extract the JSON containing "tool_call"
123
+ tool_call_dict = None
124
+ if isinstance(response.content, str):
125
+ match = re.search(r'(\{.*"tool_call".*\})', response.content, re.DOTALL)
126
+ if match:
127
+ try:
128
+ tool_call_dict = json.loads(match.group(1))
129
+ except Exception:
130
+ tool_call_dict = None
131
+ if tool_call_dict:
132
+ tool_use = tool_call_dict["tool_call"]
133
+ tool_result = await call_tool(tool_use)
134
+
135
+ messages = [
136
+ {"role": "assistant", "content": response.content},
137
+ {
138
+ "role": "user",
139
+ "content": [
140
+ {
141
+ "type": "tool_result",
142
+ "tool_use_name": tool_use["name"],
143
+ "content": str(tool_result),
144
+ }
145
+ ],
146
+ },
147
+ ]
148
+
149
+ chat_messages.extend(messages)
150
+
151
+ response = await call_ollama(chat_messages)
152
+
153
+ final_response = next((block.text for block in response.content if hasattr(block, "text")), None)
154
+ final_response = final_response or response.content
155
+
156
+ chat_messages = cl.user_session.get("chat_messages")
157
+ chat_messages.append({"role": "assistant", "content": final_response})
158
+
159
+ # Send a response back to the user
160
+ await cl.Message(content=str(response.content)).send()
quick_pp/api/router.py ADDED
@@ -0,0 +1,18 @@
1
+ from fastapi import APIRouter
2
+
3
+ from .services.las_handler import router as las_router
4
+ from .services.lithology import router as lithology_router
5
+ from .services.porosity import router as porosity_router
6
+ from .services.saturation import router as saturation_router
7
+ from .services.permeability import router as permeability_router
8
+ from .services.reservoir_summary import router as ressum_router
9
+
10
+
11
+ api_router = APIRouter(prefix="/quick_pp")
12
+
13
+ api_router.include_router(las_router)
14
+ api_router.include_router(lithology_router)
15
+ api_router.include_router(porosity_router)
16
+ api_router.include_router(saturation_router)
17
+ api_router.include_router(permeability_router)
18
+ api_router.include_router(ressum_router)