Metadata-Version: 2.4
Name: fundamental-client
Version: 0.4.3
Summary: Scikit-learn–compatible client SDK for NEXUS, Fundamental's large model for tabular data
Project-URL: documentation, https://launch.fundamental.tech/docs/guides/sdk/user-guide
Author-email: Fundamental Tech <support@fundamental.tech>
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright [yyyy] [name of copyright owner]
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
License-File: LICENSE
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: MacOS
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: httpx>=0.25.2
Requires-Dist: numpy<3.0.0,>=1.26.4
Requires-Dist: pandas<3.0.0,>=2.0.0; python_version < '3.13'
Requires-Dist: pandas<3.0.0,>=2.3.0; python_version >= '3.13'
Requires-Dist: pyarrow>=19.0.0
Requires-Dist: pydantic<3.0.0,>=2.10.0
Requires-Dist: safetensors>=0.5.0
Requires-Dist: scikit-learn<2.0.0,>=1.5.0
Provides-Extra: aws-marketplace
Requires-Dist: boto3>=1.34.0; extra == 'aws-marketplace'
Provides-Extra: dev
Requires-Dist: datamodel-code-generator[http]>=0.26.0; extra == 'dev'
Requires-Dist: minimum-dependencies; extra == 'dev'
Requires-Dist: mypy>=1.18.2; extra == 'dev'
Requires-Dist: nox; extra == 'dev'
Requires-Dist: pre-commit>=4.3.0; extra == 'dev'
Requires-Dist: pyright>=1.1.405; extra == 'dev'
Requires-Dist: pytest-cov>=7.0.0; extra == 'dev'
Requires-Dist: pytest-mock>=3.15.1; extra == 'dev'
Requires-Dist: pytest>=8.4.2; extra == 'dev'
Requires-Dist: python-dotenv>=1.0.0; extra == 'dev'
Requires-Dist: ruff>=0.13.1; extra == 'dev'
Description-Content-Type: text/markdown

# Fundamental Python SDK

[![PyPI version](https://img.shields.io/pypi/v/fundamental-client.svg?label=pypi%20package)](https://pypi.org/project/fundamental-client/)
[![Python Versions](https://img.shields.io/pypi/pyversions/fundamental-client?color=%2334D058)](https://pypi.org/project/fundamental-client)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)

A scikit-learn compatible Python SDK for NEXUS, Fundamental's large model for tabular data.

## Table of Contents

- [Installation](#installation)
- [Usage](#usage)
  - [Quick Start](#quick-start)
  - [Using Pre-trained Models](#using-pre-trained-models)
  - [Async Training](#async-training)
  - [Model Management](#model-management)
  - [Explainability & Insights](#explainability--insights)
    - [Feature Importance](#feature-importance)
- [Configuration](#configuration)
  - [Client Configuration](#client-configuration)
    - [API Key](#api-key)
    - [AWS Marketplace](#aws-marketplace)
    - [Timeouts and Retries](#timeouts-and-retries)
    - [SSL Verification](#ssl-verification)
  - [Model Configuration](#model-configuration)
    - [Mode](#mode)
- [Supported Data Types](#supported-data-types)
- [Handling Errors](#handling-errors)
  - [Diagnostics and Support Information](#diagnostics-and-support-information)
  - [Exception Types](#exception-types)
- [Troubleshooting](#troubleshooting)
- [Versioning](#versioning)
- [Requirements](#requirements)
- [License](#license)
- [Security](#security)
- [Support](#support)

## Installation

```sh
# install from PyPI
pip install fundamental-client
```

## Usage

The Fundamental SDK provides scikit-learn compatible estimators for classification and regression tasks, along with a flexible client for API interactions.


### Quick Start

Make sure `FUNDAMENTAL_API_KEY` is set (or call `fundamental.set_client(...)`) before running the examples below.

```python
from sklearn.datasets import load_breast_cancer, load_diabetes
from sklearn.model_selection import train_test_split
from fundamental import NEXUSClassifier, NEXUSRegressor

# Load classification data
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, random_state=42)

# Classification
classifier = NEXUSClassifier()
classifier.fit(X_train, y_train)

# After fitting, the model ID can be saved and used later
print(f"Trained model ID: {classifier.trained_model_id_}")

predictions = classifier.predict(X_test)
probabilities = classifier.predict_proba(X_test)

# Load regression data
X, y = load_diabetes(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, random_state=42)

# Regression
regressor = NEXUSRegressor()
regressor.fit(X_train, y_train)
predictions = regressor.predict(X_test)
```

### Using Pre-trained Models

If you have a trained model from a previous session, you can use it directly without retraining:

```python
from fundamental import NEXUSClassifier, NEXUSRegressor

classifier = NEXUSClassifier().load_model(trained_model_id="model_abc123")
predictions = classifier.predict(X_test)
probabilities = classifier.predict_proba(X_test)

regressor = NEXUSRegressor().load_model(trained_model_id="model_def456")
predictions = regressor.predict(X_test)
```

### Async Training

Model training is often a long-running operation. To support non-blocking workflows, you can submit training via `submit_fit_task()` and poll for completion. Once submitted, the training job runs in the background and its status can be queried at any time — even from a different session or process.

```python
from fundamental import NEXUSClassifier
import time

classifier = NEXUSClassifier()

# Submit training task without waiting
task_id = classifier.submit_fit_task(X_train, y_train)
print(f"Training task submitted: {task_id}")

# Poll status periodically
result = None
while result is None:
    result = classifier.poll_fit_result(task_id)
    if result is None:
        print("Training in progress...")
        time.sleep(10)  # Wait before polling again

# Model is now fitted and ready for predictions
predictions = classifier.predict(X_test)
```

#### Cross-Session Polling

Since `submit_fit_task` returns a plain task ID string, you can save it and resume polling from a different session:

```python
# Session 1: submit and save the task ID
classifier = NEXUSClassifier()
task_id = classifier.submit_fit_task(X_train, y_train)
print(f"Save this task ID: {task_id}")

# Session 2: resume polling with the saved task ID
classifier = NEXUSClassifier()
result = classifier.poll_fit_result(task_id)
if result is not None:
    predictions = classifier.predict(X_test)
```

> **Note**: Task status is available for up to 48 hours after submission.

### Model Management

The client provides methods for managing your trained models:

```python
from fundamental import Fundamental

# Create a client
client = Fundamental()

# List all available models
models = client.models.list()
print(f"Available models: {models}")

# Get information about a specific model
model_info = client.models.get("model_id_123")
print(f"Model info: {model_info}")
print(f"Attributes: {model_info.attributes}")

# Delete a model
client.models.delete("model_id_123")
```

#### Model Attributes

You can set attributes on your models to help organize and identify them.
We recommend always setting a `name` attribute; if omitted, the name will default to
`<model_version> [id:<model_id_suffix>]`.

```python
# Set attributes directly on a fitted model
classifier.set_attributes({"name": "Breast Cancer Classifier", "stage": "prod"})

# Or using the client
client.models.set_attributes(
    "model_id_123",
    attributes={"name": "Breast Cancer Classifier", "description": "Production model v1"}
)
```

### Explainability & Insights

#### Feature Importance

After fitting a model, you can compute feature importance to quantify the contribution of each input feature to the model's output:

```python
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from fundamental import NEXUSClassifier


# Load data
X, y = load_breast_cancer(return_X_y=True)
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.5, random_state=42)
# Fit the model
classifier = NEXUSClassifier()
classifier.fit(X_train, y_train)
# Get feature importance (waits for computation to complete)
feature_importance = classifier.get_feature_importance(X_val)
print(f"Feature importance: {feature_importance}")
```

Feature importance computation can take a significant amount of time. If you prefer to submit the task and check its status periodically, you can use the asynchronous approach:

```python
# Submit task without waiting
task_id = classifier.submit_feature_importance_task(X_val)

# Poll status later
result = classifier.poll_feature_importance_result(task_id)
if result is not None:
    print(f"Feature importance: {result}")
```

## Configuration

### Client Configuration

Configure the SDK client through environment variables or programmatically.

#### API Key

You can provide your API key in two ways:

```python
# 1. Programmatic
import fundamental
from fundamental import Fundamental, NEXUSClassifier

fundamental.set_client(Fundamental(api_key="your_api_key_here"))
classifier = NEXUSClassifier()
```

```bash
# 2. Environment variable
export FUNDAMENTAL_API_KEY="your_api_key_here"
```

#### AWS Marketplace

For AWS Marketplace deployments, use the `FundamentalAWSMarketplaceClient` which authenticates using AWS IAM roles via SigV4 signing instead of API keys:

```python
import fundamental
from fundamental import FundamentalAWSMarketplaceClient, NEXUSClassifier

# Set the AWS Marketplace client with your deployment URL and AWS region
fundamental.set_client(FundamentalAWSMarketplaceClient(
    aws_region="us-west-2",  # Required
    api_url="http://your-private-server:8000"
))

# Use the SDK as normal
classifier = NEXUSClassifier()
classifier.fit(X_train, y_train)
predictions = classifier.predict(X_test)
```

The `FundamentalAWSMarketplaceClient` automatically uses AWS credentials from the environment (IAM role, environment variables, or AWS config file) to sign requests. No API key is needed.

You can also configure using environment variables:

```bash
export FUNDAMENTAL_API_URL="http://your-private-server:8000"
```

```python
fundamental.set_client(
    FundamentalAWSMarketplaceClient(
        aws_region="us-west-2",  # Required
        # api_url="http://your-private-server:8000",  # Optional; overrides FUNDAMENTAL_API_URL
    )
)
```

#### Timeouts and Retries

Configure timeouts and retries when creating a client:

> **Note**: Timeouts apply only to the processing phase, starting after the dataset upload has completed.

```python
import fundamental
from fundamental import Fundamental, NEXUSClassifier

# Create and set a client with custom timeouts and retries
fundamental.set_client(Fundamental(
    fit_timeout=600,  # 10 minutes for training (default: 3 hours)
    predict_timeout=30,  # 30 seconds for predictions (default: 1 hour)
    retries=0  # Number of retries (default: 1)
))

# Estimators will use the global client
classifier = NEXUSClassifier()
```

#### SSL Verification

By default, the SDK verifies SSL certificates for all requests. To disable SSL verification:

```python
import fundamental
from fundamental import Fundamental

fundamental.set_client(Fundamental(
    api_key="your_api_key_here",
    verify_ssl=False
))
```

### Model Configuration

Configure model behavior and training parameters.

#### Mode

NEXUS offers two training modes to balance between speed and accuracy:

- **`quality` mode (default)**: Optimizes for the highest accuracy. This mode uses more comprehensive training processes and may take longer to complete.
- **`speed` mode**: Optimizes for faster training times while maintaining good accuracy.

```python
import fundamental
from fundamental import NEXUSClassifier, NEXUSRegressor

# Use quality mode (default)
classifier = NEXUSClassifier(mode="quality")
classifier.fit(X_train, y_train)

# Use speed mode for faster training
classifier_fast = NEXUSClassifier(mode="speed")
classifier_fast.fit(X_train, y_train)

# Same for regression
regressor = NEXUSRegressor(mode="speed")
regressor.fit(X_train, y_train)
```

## Supported Data Types

The SDK supports flexible input formats:

- **Input features (X)**:
  - `pandas.DataFrame`
  - `numpy.ndarray`

- **Target values (y)**:
  - `numpy.ndarray`
  - `pandas.Series`

> **Note**: Data must be serializable to Parquet via PyArrow. If you hit a serialization error, ensure columns have consistent numeric or string dtypes; complex numbers are not supported.

## Handling Errors

The SDK provides detailed error handling with specific exception types:

```python
from fundamental import NEXUSClassifier
from fundamental.exceptions import (
    NEXUSError,
    ValidationError,
    AuthenticationError,
    RateLimitError,
    ServerError
)

classifier = NEXUSClassifier()

try:
    classifier.fit(X_train, y_train)
except ValidationError as e:
    print(f"Invalid input data: {e}")
    print(f"Status code: {e.status_code}")
except AuthenticationError as e:
    print("Authentication failed - check your API key")
except RateLimitError as e:
    print("Rate limit exceeded - please wait before retrying")
except ServerError as e:
    print("Server error - please try again later")
except NEXUSError as e:
    print(f"An error occurred: {e}")
```

### Diagnostics and Support Information

All exceptions include a `trace_id` attribute that you can share with Fundamental support to help diagnose issues more quickly.

```python
except ServerError as e:
    if e.trace_id:
        print(f"Error trace_id: {e.trace_id}")
```

If you're troubleshooting an issue or need to share debug information with the Fundamental team, you can enable diagnostics to capture SDK activity and detailed error reports to a file:

```python
from fundamental.diagnostics import activate, deactivate

activate()            # logs to <tempdir>/fundamental/fundamental_debug_<timestamp>.log
# activate(log_dir="/tmp/logs")  # or specify a directory

# ... your code ...

deactivate()          # stop logging
```

Or use a context manager for scoped diagnostics:

```python
from fundamental.diagnostics import diagnose

with diagnose():
    classifier.fit(X_train, y_train)
```

The log file captures comprehensive SDK activity and produces detailed exception reports including tracebacks, trace IDs, and user source context. Secrets are automatically masked, but please review the log file before sharing it with the Fundamental team to ensure no sensitive data is included.

### Exception Types

| Error Type | Description | Status Code |
| ---------- | ----------- | ----------- |
| `ValidationError` | Input validation failed (bad request) | 400 |
| `AuthenticationError` | Authentication failed (missing/invalid API key) | 401 |
| `AuthorizationError` | Authorization failed (insufficient permissions) | 403 |
| `NotFoundError` | Resource not found | 404 |
| `RateLimitError` | API rate limit exceeded | 429 |
| `ServerError` | Server-side error | 500+ |
| `NetworkError` | Network connectivity issues | 503 |
| `RequestTimeoutError` | Request timed out | 504 |

## Troubleshooting

- **Missing API key** (`ValueError: API key is required...`): set `FUNDAMENTAL_API_KEY` or configure a client via `fundamental.set_client(...)`.
- **Serialization errors (PyArrow)**: ensure `X`/`y` contain consistent numeric or string types; avoid mixed-type/object columns.
- **Large datasets / memory use**: datasets are serialized to Parquet in-memory before upload. If you run into memory or upload issues, try sampling, reducing columns, or using batching.
- **Debugging issues**: run `from fundamental.diagnostics import activate; activate()` and share the generated log file with support.

## Versioning

This package follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions.

To check the installed version:

```python
import fundamental
print(fundamental.__version__)
```

## Requirements

- Python 3.10 or higher
- See [pyproject.toml](pyproject.toml) for full dependency list

## License

This project is licensed under the Apache License 2.0 - see the [LICENSE](LICENSE) file for details.

## Security

If you believe you’ve found a security vulnerability, please email [support@fundamental.tech](mailto:support@fundamental.tech) and include a minimal reproduction. Please do not open a public GitHub issue.

## Support

- **SDK docs**: [SDK User Guide](https://launch.fundamental.tech/docs/guides/sdk/user-guide)
- **Issues**: [GitHub Issues](https://github.com/Fundamental-Technologies/fundamental-client/issues)
- **Email**: [support@fundamental.tech](mailto:support@fundamental.tech)
