-
Notifications
You must be signed in to change notification settings - Fork 177
Add namedtuple, pyspark, ibis, lc to SDK coverage #895
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
05902c7
Adds running the SDK tests
skrawcz 6c71b3c
Adds capture of NamedTuples
skrawcz 7aa8092
Adds minimal capture of pyspark & ibis results
skrawcz 3b22a5b
Adds safety around getting module members
skrawcz 028db2c
Fixes docstring
skrawcz 1968b43
Adds basic langchain support for SDK
skrawcz b94b273
Adds missing test dependencies for SDK
skrawcz 2df0661
Adds some extra comments
skrawcz File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| name: SDK Test Workflow | ||
|
|
||
| on: | ||
| push: | ||
| branches: | ||
| - main # or any specific branches you want to include | ||
| paths: | ||
| - 'ui/sdk/**' | ||
|
|
||
| pull_request: | ||
| paths: | ||
| - 'ui/sdk/**' | ||
|
|
||
|
|
||
| jobs: | ||
| sdk-unit-test: | ||
| runs-on: ubuntu-latest | ||
| strategy: | ||
| matrix: | ||
| python-version: ['3.9', '3.10', '3.11'] | ||
| defaults: | ||
| run: | ||
| working-directory: ui/sdk | ||
| steps: | ||
| - uses: actions/checkout@v3 | ||
| - name: Set up Python ${{ matrix.python-version }} | ||
| uses: actions/setup-python@v4 | ||
| with: | ||
| python-version: ${{ matrix.python-version }} | ||
| - name: Install dependencies | ||
| run: | | ||
| python -m pip install --upgrade pip | ||
| pip install -r requirements.txt | ||
| pip install -r requirements-test.txt | ||
| pip install -e . | ||
| - name: Run unit tests | ||
| run: | | ||
| pytest tests/ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,6 @@ | ||
| ibis-framework | ||
| langchain_core | ||
| polars | ||
| pyspark | ||
| pytest | ||
| ray | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,89 @@ | ||
| from typing import Any, Dict | ||
|
|
||
| from hamilton_sdk.tracking import stats | ||
| from ibis.expr.datatypes import core | ||
|
|
||
| # import ibis.expr.types as ir | ||
| from ibis.expr.types import relations | ||
|
|
||
| """Module that houses functions to introspect an Ibis Table. We don't have expression support yet. | ||
| """ | ||
|
|
||
| base_data_type_mapping_dict = { | ||
| "timestamp": "datetime", | ||
| "date": "datetime", | ||
| "string": "str", | ||
| "integer": "numeric", | ||
| "double": "numeric", | ||
| "float": "numeric", | ||
| "boolean": "boolean", | ||
| "long": "numeric", | ||
| "short": "numeric", | ||
| } | ||
|
|
||
|
|
||
| def base_data_type_mapping(data_type: core.DataType) -> str: | ||
| """Returns the base data type of the column. | ||
| This uses the internal is_* type methods to determine the base data type. | ||
| """ | ||
| return "unhandled" # TODO: implement this | ||
|
|
||
|
|
||
| base_schema = { | ||
| # we can't get all of these about an ibis dataframe | ||
| "base_data_type": None, | ||
| # 'count': 0, | ||
| "data_type": None, | ||
| # 'histogram': {}, | ||
| # 'max': 0, | ||
| # 'mean': 0, | ||
| # 'min': 0, | ||
| # 'missing': 0, | ||
| "name": None, | ||
| "pos": None, | ||
| # 'quantiles': {}, | ||
| # 'std': 0, | ||
| # 'zeros': 0 | ||
| } | ||
|
|
||
|
|
||
| def _introspect(table: relations.Table) -> Dict[str, Any]: | ||
| """Introspect a PySpark dataframe and return a dictionary of statistics. | ||
|
|
||
| :param df: PySpark dataframe to introspect. | ||
| :return: Dictionary of column to metadata about it. | ||
| """ | ||
| # table. | ||
| fields = table.schema().items() | ||
| column_to_metadata = [] | ||
| for idx, (field_name, field_type) in enumerate(fields): | ||
| values = base_schema.copy() | ||
| values.update( | ||
| { | ||
| "name": field_name, | ||
| "pos": idx, | ||
| "data_type": str(field_type), | ||
| "base_data_type": base_data_type_mapping(field_type), | ||
| "nullable": field_type.nullable, | ||
| } | ||
| ) | ||
| column_to_metadata.append(values) | ||
| return { | ||
| "columns": column_to_metadata, | ||
| } | ||
|
|
||
|
|
||
| @stats.compute_stats.register | ||
| def compute_stats_ibis_table( | ||
| result: relations.Table, node_name: str, node_tags: dict | ||
| ) -> Dict[str, Any]: | ||
| # TODO: create custom type instead of dict for UI | ||
| o_value = _introspect(result) | ||
| return { | ||
| "observability_type": "dict", | ||
| "observability_value": { | ||
| "type": str(type(result)), | ||
| "value": o_value, | ||
| }, | ||
| "observability_schema_version": "0.0.2", | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| """ | ||
| Module to pull a few things from langchain objects. | ||
| """ | ||
|
|
||
| from typing import Any, Dict | ||
|
|
||
| from hamilton_sdk.tracking import stats | ||
| from langchain_core import documents as lc_documents | ||
| from langchain_core import messages as lc_messages | ||
|
|
||
|
|
||
| @stats.compute_stats.register(lc_messages.BaseMessage) | ||
| def compute_stats_lc_messages( | ||
| result: lc_messages.BaseMessage, node_name: str, node_tags: dict | ||
| ) -> Dict[str, Any]: | ||
| result = {"value": result.content, "type": result.type} | ||
|
|
||
| return { | ||
| "observability_type": "dict", | ||
| "observability_value": result, | ||
| "observability_schema_version": "0.0.2", | ||
| } | ||
|
|
||
|
|
||
| @stats.compute_stats.register(lc_documents.Document) | ||
| def compute_stats_lc_docs( | ||
| result: lc_documents.Document, node_name: str, node_tags: dict | ||
| ) -> Dict[str, Any]: | ||
| if hasattr(result, "to_document"): | ||
| return stats.compute_stats(result.to_document(), node_name, node_tags) | ||
| else: | ||
| # d.page_content # hack because not all documents are serializable | ||
| result = {"content": result.page_content, "metadata": result.metadata} | ||
| return { | ||
| "observability_type": "dict", | ||
| "observability_value": result, | ||
| "observability_schema_version": "0.0.2", | ||
| } | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| # Example usage | ||
| from langchain_core import messages | ||
|
|
||
| msg = messages.BaseMessage(content="Hello, World!", type="greeting") | ||
| print(stats.compute_stats(msg, "greeting", {})) | ||
|
|
||
| doc = lc_documents.Document(page_content="Hello, World!", metadata={"source": "local_dir"}) | ||
| print(stats.compute_stats(doc, "document", {})) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,110 @@ | ||
| from typing import Any, Dict | ||
|
|
||
| import pyspark.sql as ps | ||
| from hamilton_sdk.tracking import stats | ||
|
|
||
| """Module that houses functions to introspect a PySpark dataframe. | ||
| """ | ||
| # this is a mapping used in the Backend/UI. | ||
| # we should probably move this to a shared location. | ||
| base_data_type_mapping = { | ||
| "timestamp": "datetime", | ||
| "date": "datetime", | ||
| "string": "str", | ||
| "integer": "numeric", | ||
| "double": "numeric", | ||
| "float": "numeric", | ||
| "boolean": "boolean", | ||
| "long": "numeric", | ||
| "short": "numeric", | ||
| } | ||
|
|
||
| base_schema = { | ||
| # we can't get all of these about a pyspark dataframe | ||
| "base_data_type": None, | ||
| # 'count': 0, | ||
| "data_type": None, | ||
| # 'histogram': {}, | ||
| # 'max': 0, | ||
| # 'mean': 0, | ||
| # 'min': 0, | ||
| # 'missing': 0, | ||
| "name": None, | ||
| "pos": None, | ||
| # 'quantiles': {}, | ||
| # 'std': 0, | ||
| # 'zeros': 0 | ||
| } | ||
|
|
||
|
|
||
| def _introspect(df: ps.DataFrame) -> Dict[str, Any]: | ||
| """Introspect a PySpark dataframe and return a dictionary of statistics. | ||
|
|
||
| :param df: PySpark dataframe to introspect. | ||
| :return: Dictionary of column to metadata about it. | ||
| """ | ||
| fields = df.schema.jsonValue()["fields"] | ||
| column_to_metadata = [] | ||
| for idx, field in enumerate(fields): | ||
| values = base_schema.copy() | ||
| values.update( | ||
| { | ||
| "name": field["name"], | ||
| "pos": idx, | ||
| "data_type": field["type"], | ||
| "base_data_type": base_data_type_mapping.get(field["type"], "unhandled"), | ||
| "nullable": field["nullable"], | ||
| } | ||
| ) | ||
| column_to_metadata.append(values) | ||
| cost_explain = df._sc._jvm.PythonSQLUtils.explainString(df._jdf.queryExecution(), "cost") | ||
| extended_explain = df._sc._jvm.PythonSQLUtils.explainString( | ||
| df._jdf.queryExecution(), "extended" | ||
| ) | ||
| return { | ||
| "columns": column_to_metadata, | ||
| "cost_explain": cost_explain, | ||
| "extended_explain": extended_explain, | ||
| } | ||
|
|
||
|
|
||
| @stats.compute_stats.register | ||
| def compute_stats_psdf(result: ps.DataFrame, node_name: str, node_tags: dict) -> Dict[str, Any]: | ||
| # TODO: create custom type instead of dict for UI | ||
| o_value = _introspect(result) | ||
| return { | ||
| "observability_type": "dict", | ||
| "observability_value": { | ||
| "type": str(type(result)), | ||
| "value": o_value, | ||
| }, | ||
| "observability_schema_version": "0.0.2", | ||
| } | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| import numpy as np | ||
| import pandas as pd | ||
|
|
||
| df = pd.DataFrame( | ||
| { | ||
| "a": [1, 2, 3, 4, 5], | ||
| "b": ["a", "b", "c", "d", "e"], | ||
| "c": [True, False, True, False, True], | ||
| "d": [1.0, 2.0, 3.0, 4.0, 5.0], | ||
| "e": pd.Categorical(["a", "b", "c", "d", "e"]), | ||
| "f": pd.Series(["a", "b", "c", "d", "e"], dtype="string"), | ||
| "g": pd.Series(["a", "b", "c", "d", "e"], dtype="object"), | ||
| "h": pd.Series( | ||
| ["20221231", None, "20221231", "20221231", "20221231"], dtype="datetime64[ns]" | ||
| ), | ||
| "i": pd.Series([None, None, None, None, None], name="a", dtype=np.float64), | ||
| "j": pd.Series(name="a", data=pd.date_range("20230101", "20230105")), | ||
| } | ||
| ) | ||
| spark = ps.SparkSession.builder.master("local[1]").getOrCreate() | ||
| psdf = spark.createDataFrame(df) | ||
| import pprint | ||
|
|
||
| res = compute_stats_psdf(psdf, "df", {}) | ||
| pprint.pprint(res) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.