predikit 0.1.0__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.
predikit/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ from .tool import ModelTool
2
+ from .registry import ToolRegistry
3
+
4
+ __all__ = ["ModelTool", "ToolRegistry"]
5
+ __version__ = "0.1.0"
predikit/coerce.py ADDED
@@ -0,0 +1,50 @@
1
+ from typing import Any
2
+ from pydantic import BaseModel
3
+
4
+
5
+ _BOOL_TRUE = {"true", "1", "yes", "on"}
6
+ _BOOL_FALSE = {"false", "0", "no", "off"}
7
+
8
+
9
+ def coerce_value(value: Any, target_type: type) -> Any:
10
+ """Coerce a single value to target_type with LLM-friendly string handling."""
11
+ if isinstance(value, target_type):
12
+ return value
13
+
14
+ if target_type is bool:
15
+ if isinstance(value, str):
16
+ low = value.lower()
17
+ if low in _BOOL_TRUE:
18
+ return True
19
+ if low in _BOOL_FALSE:
20
+ return False
21
+ raise ValueError(f"Cannot interpret {value!r} as bool. Expected one of: true/false, yes/no, 1/0, on/off")
22
+ return bool(value)
23
+
24
+ if target_type is int:
25
+ return int(float(value))
26
+
27
+ if target_type is float:
28
+ return float(value)
29
+
30
+ if target_type is str:
31
+ return str(value)
32
+
33
+ return value
34
+
35
+
36
+ def coerce_inputs(validated: BaseModel, meta: dict) -> list:
37
+ """Return feature values in the order the model expects them."""
38
+ data = validated.model_dump()
39
+ feature_names = meta.get("feature_names")
40
+ if feature_names:
41
+ missing = [f for f in feature_names if f not in data]
42
+ if missing:
43
+ raise ValueError(
44
+ f"Input schema is missing model features: {missing}. "
45
+ f"Field names in your Pydantic schema must exactly match the column names "
46
+ f"used during model training. "
47
+ f"Schema has: {list(data.keys())}, model expects: {feature_names}"
48
+ )
49
+ return [data[f] for f in feature_names]
50
+ return list(data.values())
File without changes
@@ -0,0 +1,25 @@
1
+ from __future__ import annotations
2
+ from typing import TYPE_CHECKING
3
+
4
+ if TYPE_CHECKING:
5
+ from ..tool import ModelTool
6
+
7
+
8
+ def to_langchain_tool(tool: ModelTool):
9
+ """Convert a ModelTool to a LangChain StructuredTool."""
10
+ try:
11
+ from langchain_core.tools import StructuredTool
12
+ except ImportError:
13
+ raise ImportError(
14
+ "langchain-core is required. Install with: pip install predikit[langchain]"
15
+ )
16
+
17
+ def _run(**kwargs) -> dict:
18
+ return tool.invoke(kwargs)
19
+
20
+ return StructuredTool.from_function(
21
+ func=_run,
22
+ name=tool.name,
23
+ description=tool.description,
24
+ args_schema=tool.input_schema,
25
+ )
@@ -0,0 +1,20 @@
1
+ from __future__ import annotations
2
+ from typing import TYPE_CHECKING
3
+
4
+ if TYPE_CHECKING:
5
+ from ..tool import ModelTool
6
+
7
+
8
+ def to_openai_schema(tool: ModelTool) -> dict:
9
+ """Convert a ModelTool to an OpenAI function-calling schema dict."""
10
+ schema = tool.input_schema.model_json_schema()
11
+ schema.pop("title", None)
12
+
13
+ return {
14
+ "type": "function",
15
+ "function": {
16
+ "name": tool.name,
17
+ "description": tool.description,
18
+ "parameters": schema,
19
+ },
20
+ }
predikit/introspect.py ADDED
@@ -0,0 +1,22 @@
1
+ from typing import Any
2
+
3
+
4
+ def introspect(model: Any) -> dict:
5
+ """Extract metadata from a fitted sklearn-compatible estimator."""
6
+ meta: dict = {}
7
+
8
+ meta["feature_names"] = (
9
+ list(model.feature_names_in_) if hasattr(model, "feature_names_in_") else None
10
+ )
11
+ meta["n_features"] = (
12
+ int(model.n_features_in_) if hasattr(model, "n_features_in_") else None
13
+ )
14
+
15
+ if hasattr(model, "classes_"):
16
+ meta["task"] = "classification"
17
+ meta["classes"] = list(model.classes_)
18
+ else:
19
+ meta["task"] = "regression"
20
+ meta["classes"] = None
21
+
22
+ return meta
predikit/registry.py ADDED
@@ -0,0 +1,20 @@
1
+ from __future__ import annotations
2
+ from .tool import ModelTool
3
+
4
+
5
+ class ToolRegistry:
6
+ """Bundles multiple ModelTools and provides bulk export methods."""
7
+
8
+ def __init__(self, tools: list[ModelTool]) -> None:
9
+ self._tools: dict[str, ModelTool] = {t.name: t for t in tools}
10
+
11
+ def get(self, name: str) -> ModelTool:
12
+ if name not in self._tools:
13
+ raise KeyError(f"No tool named '{name}'. Available: {list(self._tools)}")
14
+ return self._tools[name]
15
+
16
+ def to_openai(self) -> list[dict]:
17
+ return [t.to_openai() for t in self._tools.values()]
18
+
19
+ def to_langchain(self) -> list:
20
+ return [t.to_langchain() for t in self._tools.values()]
predikit/tool.py ADDED
@@ -0,0 +1,93 @@
1
+ from __future__ import annotations
2
+ from typing import Any, Callable
3
+
4
+ import numpy as np
5
+ from pydantic import BaseModel
6
+
7
+ from .introspect import introspect
8
+ from .coerce import coerce_inputs, coerce_value
9
+ from .exporters.openai import to_openai_schema
10
+ from .exporters.langchain import to_langchain_tool
11
+
12
+ # Only apply pre-coercion for these scalar types; everything else goes straight to Pydantic.
13
+ _SCALAR_TYPES = (bool, int, float, str)
14
+
15
+
16
+ class ModelTool:
17
+ """Wraps a fitted sklearn-compatible model as an LLM-callable tool."""
18
+
19
+ def __init__(
20
+ self,
21
+ model: Any,
22
+ name: str,
23
+ description: str,
24
+ input_schema: type[BaseModel],
25
+ output_name: str,
26
+ output_description: str,
27
+ ) -> None:
28
+ self.model = model
29
+ self.name = name
30
+ self.description = description
31
+ self.input_schema = input_schema
32
+ self.output_name = output_name
33
+ self.output_description = output_description
34
+ self._meta = introspect(model)
35
+
36
+ def invoke(self, input_dict: dict) -> dict:
37
+ """Validate inputs, run prediction, return {output_name: value}."""
38
+ pre_coerced = self._pre_coerce(input_dict)
39
+ try:
40
+ validated = self.input_schema(**pre_coerced)
41
+ except Exception as exc:
42
+ raise ValueError(f"Input validation failed for '{self.name}': {exc}") from exc
43
+
44
+ features = coerce_inputs(validated, self._meta)
45
+ X = self._to_array(features)
46
+ prediction = self.model.predict(X)[0]
47
+
48
+ if hasattr(prediction, "item"):
49
+ prediction = prediction.item()
50
+
51
+ return {self.output_name: prediction}
52
+
53
+ def to_openai(self) -> dict:
54
+ """Return an OpenAI function-calling schema dict."""
55
+ return to_openai_schema(self)
56
+
57
+ def to_langchain(self):
58
+ """Return a LangChain StructuredTool."""
59
+ return to_langchain_tool(self)
60
+
61
+ def to_callable(self) -> Callable[..., dict]:
62
+ """Return a plain Python function that calls invoke()."""
63
+ def _fn(**kwargs) -> dict:
64
+ return self.invoke(kwargs)
65
+ _fn.__name__ = self.name
66
+ _fn.__doc__ = self.description
67
+ return _fn
68
+
69
+ def _pre_coerce(self, input_dict: dict) -> dict:
70
+ # Runs coerce_value before Pydantic so LLM strings like "yes"/"no" work for bool fields.
71
+ fields = self.input_schema.model_fields
72
+ result = {}
73
+ for k, v in input_dict.items():
74
+ field = fields.get(k)
75
+ annotation = getattr(field, "annotation", None) if field else None
76
+ if annotation in _SCALAR_TYPES:
77
+ try:
78
+ result[k] = coerce_value(v, annotation)
79
+ except (ValueError, TypeError):
80
+ result[k] = v # let Pydantic surface the error with full context
81
+ else:
82
+ result[k] = v
83
+ return result
84
+
85
+ def _to_array(self, features: list) -> Any:
86
+ feature_names = self._meta.get("feature_names")
87
+ if feature_names:
88
+ try:
89
+ import pandas as pd
90
+ return pd.DataFrame([dict(zip(feature_names, features))])
91
+ except ImportError:
92
+ pass
93
+ return np.array([features])
@@ -0,0 +1,233 @@
1
+ Metadata-Version: 2.4
2
+ Name: predikit
3
+ Version: 0.1.0
4
+ Summary: Turn any trained sklearn/XGBoost model into an LLM-callable tool with auto-generated schemas and typed I/O.
5
+ Project-URL: Homepage, https://github.com/Tejas-TA/predikit
6
+ Project-URL: Repository, https://github.com/Tejas-TA/predikit
7
+ Author-email: Tejas Tumakuru Ashok <tejas.tumakuruashok@travelandleisure.com>
8
+ License: MIT
9
+ License-File: LICENSE
10
+ Keywords: agents,function-calling,llm,ml-tools,sklearn,xgboost
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
20
+ Requires-Python: >=3.10
21
+ Requires-Dist: numpy>=1.24
22
+ Requires-Dist: pydantic>=2.0
23
+ Requires-Dist: scikit-learn>=1.2
24
+ Provides-Extra: dev
25
+ Requires-Dist: langchain-core>=0.1; extra == 'dev'
26
+ Requires-Dist: pandas>=1.5; extra == 'dev'
27
+ Requires-Dist: pytest-cov>=4.0; extra == 'dev'
28
+ Requires-Dist: pytest>=7.0; extra == 'dev'
29
+ Requires-Dist: xgboost>=1.7; extra == 'dev'
30
+ Provides-Extra: langchain
31
+ Requires-Dist: langchain-core>=0.1; extra == 'langchain'
32
+ Provides-Extra: xgboost
33
+ Requires-Dist: xgboost>=1.7; extra == 'xgboost'
34
+ Description-Content-Type: text/markdown
35
+
36
+ # predikit
37
+
38
+ Turn any trained scikit-learn or XGBoost model into an LLM-callable tool — auto-generated JSON schemas, typed I/O, zero boilerplate.
39
+
40
+ ```python
41
+ tool = ModelTool(model=clf, name="classify_iris", ...)
42
+ tool.to_openai() # OpenAI function schema, ready to pass to the API
43
+ tool.invoke({"sqft": 2200}) # → {"price_usd": 370730}
44
+ ```
45
+
46
+ ## Install
47
+
48
+ ```bash
49
+ pip install predikit
50
+
51
+ # With XGBoost support
52
+ pip install predikit[xgboost]
53
+
54
+ # With LangChain support
55
+ pip install predikit[langchain]
56
+ ```
57
+
58
+ ## 30-second example
59
+
60
+ ```python
61
+ from pydantic import BaseModel, Field
62
+ from sklearn.datasets import load_iris
63
+ from sklearn.linear_model import LogisticRegression
64
+ from predikit import ModelTool
65
+
66
+ # Train
67
+ X, y = load_iris(return_X_y=True)
68
+ clf = LogisticRegression(max_iter=200).fit(X, y)
69
+
70
+ # Define what the LLM will pass in
71
+ class IrisInput(BaseModel):
72
+ sepal_length: float = Field(description="Sepal length in cm")
73
+ sepal_width: float = Field(description="Sepal width in cm")
74
+ petal_length: float = Field(description="Petal length in cm")
75
+ petal_width: float = Field(description="Petal width in cm")
76
+
77
+ # Wrap the model
78
+ tool = ModelTool(
79
+ model=clf,
80
+ name="classify_iris",
81
+ description="Classify an iris flower: 0=setosa, 1=versicolor, 2=virginica.",
82
+ input_schema=IrisInput,
83
+ output_name="species",
84
+ output_description="Predicted species index",
85
+ )
86
+
87
+ # Get an OpenAI-ready schema
88
+ import json
89
+ print(json.dumps(tool.to_openai(), indent=2))
90
+
91
+ # Call it directly
92
+ tool.invoke({
93
+ "sepal_length": 5.1, "sepal_width": 3.5,
94
+ "petal_length": 1.4, "petal_width": 0.2,
95
+ })
96
+ # → {"species": 0}
97
+ ```
98
+
99
+ ## Core API
100
+
101
+ ### `ModelTool`
102
+
103
+ ```python
104
+ ModelTool(
105
+ model, # fitted sklearn-compatible estimator
106
+ name: str, # tool name the LLM sees
107
+ description: str, # tool description the LLM sees
108
+ input_schema, # Pydantic BaseModel describing inputs
109
+ output_name: str, # key for the prediction in the returned dict
110
+ output_description: str,
111
+ )
112
+ ```
113
+
114
+ | Method | Returns | What it does |
115
+ |--------|---------|--------------|
116
+ | `.invoke(input_dict)` | `dict` | Validates → predicts → returns `{output_name: value}` |
117
+ | `.to_openai()` | `dict` | OpenAI function-calling schema |
118
+ | `.to_langchain()` | `StructuredTool` | LangChain tool |
119
+ | `.to_callable()` | `Callable` | Plain Python function |
120
+
121
+ ### `ToolRegistry`
122
+
123
+ Group multiple tools for bulk export:
124
+
125
+ ```python
126
+ registry = ToolRegistry([price_tool, risk_tool])
127
+ registry.to_openai() # → list[dict], pass directly to OpenAI
128
+ registry.to_langchain() # → list[StructuredTool]
129
+ registry.get("name") # → ModelTool
130
+ ```
131
+
132
+ ## Field naming rule
133
+
134
+ **Your Pydantic schema field names must exactly match the column names the model was trained on.**
135
+
136
+ predikit maps inputs to features by name, not position. If you trained on a DataFrame with columns `["sqft", "bedrooms"]`, your schema fields must be `sqft` and `bedrooms` — not `sq_ft`, not `Sqft`.
137
+
138
+ ```python
139
+ # ✓ Columns match: sqft, bedrooms, bathrooms
140
+ class GoodInput(BaseModel):
141
+ sqft: float
142
+ bedrooms: float
143
+ bathrooms: float
144
+
145
+ # ✗ Name mismatch — raises ValueError at runtime
146
+ class BadInput(BaseModel):
147
+ square_footage: float # model expects "sqft"
148
+ beds: float # model expects "bedrooms"
149
+ baths: float # model expects "bathrooms"
150
+ ```
151
+
152
+ When there's a mismatch, predikit tells you exactly which names are wrong:
153
+
154
+ ```
155
+ ValueError: Input schema is missing model features: ['sqft', 'bedrooms'].
156
+ Schema has: ['square_footage', 'beds', 'bathrooms'], model expects: ['sqft', 'bedrooms', 'bathrooms']
157
+ ```
158
+
159
+ > **Tip:** If you trained with a numpy array (no DataFrame), predikit has no feature names to check — it uses your schema's field definition order instead.
160
+
161
+ ## Cookbook
162
+
163
+ ### XGBoost regression
164
+
165
+ ```python
166
+ from xgboost import XGBRegressor
167
+ from predikit import ModelTool
168
+
169
+ reg = XGBRegressor().fit(X_train, y_train)
170
+
171
+ class HouseInput(BaseModel):
172
+ sqft: float
173
+ bedrooms: float
174
+ year_built: float
175
+
176
+ tool = ModelTool(
177
+ model=reg,
178
+ name="price_estimate",
179
+ description="Predict home price in USD.",
180
+ input_schema=HouseInput,
181
+ output_name="price_usd",
182
+ output_description="Predicted sale price in USD",
183
+ )
184
+ ```
185
+
186
+ ### Multiple tools in one registry
187
+
188
+ ```python
189
+ registry = ToolRegistry([price_tool, risk_tool, demand_tool])
190
+
191
+ # OpenAI
192
+ response = client.chat.completions.create(
193
+ model="gpt-4o",
194
+ tools=registry.to_openai(),
195
+ ...
196
+ )
197
+
198
+ # LangChain
199
+ agent = initialize_agent(tools=registry.to_langchain(), ...)
200
+ ```
201
+
202
+ ### Bool inputs from an LLM
203
+
204
+ LLMs sometimes return `"yes"`, `"true"`, or `"1"` for boolean fields. predikit coerces these automatically before Pydantic validation:
205
+
206
+ ```python
207
+ class Input(BaseModel):
208
+ has_pool: bool
209
+
210
+ tool.invoke({"has_pool": "yes"}) # → coerced to True
211
+ tool.invoke({"has_pool": "false"}) # → coerced to False
212
+ tool.invoke({"has_pool": "maybe"}) # → raises ValueError with clear message
213
+ ```
214
+
215
+ Supported strings: `true/false`, `yes/no`, `1/0`, `on/off`.
216
+
217
+ ### Orlando real estate demo
218
+
219
+ See [`examples/03_orlando_real_estate.py`](examples/03_orlando_real_estate.py) for a full end-to-end walkthrough: synthetic dataset → XGBoost training → `ModelTool` → registry → OpenAI schema → prediction.
220
+
221
+ ## Roadmap
222
+
223
+ Intentionally out of scope for v0.1 — planned for later releases:
224
+
225
+ - Confidence-aware routing & fallback
226
+ - Multi-model synthesis (agent calls several, reconciles results)
227
+ - MLflow / Snowflake Model Registry integration
228
+ - HuggingFace / PyTorch / TensorFlow support
229
+ - Async invocation
230
+
231
+ ## License
232
+
233
+ MIT © Tejas Tumakuru Ashok
@@ -0,0 +1,12 @@
1
+ predikit/__init__.py,sha256=pybtPHFnZV9Q8yyLXA-cCtbZcLL1f_jbERBQboEfZfU,126
2
+ predikit/coerce.py,sha256=Pw0CwSgDBvW0j5zYbQyRd1jX3dr6j9Gcx-FgT91fWuc,1629
3
+ predikit/introspect.py,sha256=0J71ye3YC6y473Uui5rAO58yBVI39jB0y3KKFIlfgIM,606
4
+ predikit/registry.py,sha256=bH3ulINhbzy9y67vsbgo94lNOBvuWmUR8FGzKjx5JJY,686
5
+ predikit/tool.py,sha256=xyV_r65-CfnhmMtRkFbNoBhsgpkzEkXMJTbJlY0UKCc,3224
6
+ predikit/exporters/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ predikit/exporters/langchain.py,sha256=2-ut2OT90JuZWK1rZheUtKzaPmK_JwwLYrReNpcmLgY,673
8
+ predikit/exporters/openai.py,sha256=GWaffvb6FFI8tlqI9UlLi-u5n3-YT2ikKvj5UpHrCWA,514
9
+ predikit-0.1.0.dist-info/METADATA,sha256=hedfKoGKoHWBmTLh9tmTTu1-yqYv3KjVGFHP62QJuoQ,7115
10
+ predikit-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
11
+ predikit-0.1.0.dist-info/licenses/LICENSE,sha256=wszEW4O1EXHs-UrAlT3-5HEFG78t1QVc4u4jymKPWiI,1077
12
+ predikit-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tejas Tumakuru Ashok
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.