repo_name
stringlengths
1
62
dataset
stringclasses
1 value
lang
stringclasses
11 values
pr_id
int64
1
20.1k
owner
stringlengths
2
34
reviewer
stringlengths
2
39
diff_hunk
stringlengths
15
262k
code_review_comment
stringlengths
1
99.6k
pyspark-ai
github_2023
others
162
pyspark-ai
gengliangwang
@@ -22,29 +22,43 @@ classifiers = [ ] [tool.poetry.dependencies] +# default required dependencies python = "^3.8.1" pydantic = "^1.10.10" -requests = "^2.31.0" -tiktoken = "0.4.0" -beautifulsoup4 = "^4.12.2" openai = "^0.27.8" langchain = ">=0.0.271,<0.1.0" -pandas = ">=1.0.5" pygments = "^2.15.1" -google-api-python-client = "^2.90.0" -chispa = "^0.9.2" -grpcio = ">=1.56.0" -plotly = "^5.15.0" -pyarrow = ">=4.0.0" -grpcio-status = ">=1.56.0" -faiss-cpu = "^1.7.4" -sentence-transformers = "^2.2.2" -torch = ">=2.0.0, !=2.0.1" - -[tool.poetry.dev-dependencies] + +# optional dependencies, opted into by groups + +# dependencies for create +requests = { version = "^2.31.0", optional = true } +tiktoken = { version = "0.4.0", optional = true } +beautifulsoup4 = { version = "^4.12.2", optional = true } +google-api-python-client = { version = "^2.90.0", optional = true } + +# dependencies for plot +pandas = { version = ">=1.0.5", optional = true, extras = ["all"]} +grpcio = { version = ">=1.56.0", optional = true} +plotly = { version = "^5.15.0", optional = true } +pyarrow = { version = ">=4.0.0", optional = true }
This is for Spark connect, too
pyspark-ai
github_2023
others
162
pyspark-ai
gengliangwang
@@ -24,27 +24,41 @@ classifiers = [ [tool.poetry.dependencies] python = "^3.8.1" pydantic = "^1.10.10" -requests = "^2.31.0" -tiktoken = "0.4.0" -beautifulsoup4 = "^4.12.2" openai = "^0.27.8" langchain = ">=0.0.271,<0.1.0" -pandas = ">=1.0.5" pygments = "^2.15.1" -google-api-python-client = "^2.90.0" -chispa = "^0.9.2" -grpcio = ">=1.56.0" + +[tool.poetry.group.plot.dependencies] +pandas = ">=1.0.5" plotly = "^5.15.0" -pyarrow = ">=4.0.0" -grpcio-status = ">=1.56.0" + +[tool.poetry.group.vector-search.dependencies] faiss-cpu = "^1.7.4" sentence-transformers = "^2.2.2" -torch = ">=2.0.0, !=2.0.1" +torch = ">=2.0.0, !=2.0.1, !=2.1.0"
Why it can't be 2.1.0? let's add a comment
pyspark-ai
github_2023
python
162
pyspark-ai
gengliangwang
@@ -43,6 +39,15 @@ ) from pyspark_ai.spark_utils import SparkUtils +create_deps_requirement_message = None +try:
let's move the try..catch to method `create_df`?
pyspark-ai
github_2023
python
162
pyspark-ai
gengliangwang
@@ -62,7 +67,7 @@ def __init__( cache_file_location: Optional[str] = None, vector_store_dir: Optional[str] = None, vector_store_max_gb: Optional[float] = 16, - encoding: Optional[Encoding] = None, + encoding: "Optional[Encoding]" = None,
I suspect if anyone specifies this option...How about let's just remove it and mention it in the PR description.
pyspark-ai
github_2023
python
162
pyspark-ai
gengliangwang
@@ -113,7 +118,8 @@ def __init__( self._cache = None self._vector_store_dir = vector_store_dir self._vector_store_max_gb = vector_store_max_gb - self._encoding = encoding or tiktoken.get_encoding("cl100k_base") + if not create_deps_requirement_message: + self._encoding = encoding or tiktoken.get_encoding("cl100k_base")
As per https://github.com/pyspark-ai/pyspark-ai/pull/162/files#r1361217186, we can now move the encoding into method `create_df`
pyspark-ai
github_2023
python
162
pyspark-ai
gengliangwang
@@ -173,8 +173,13 @@ def vector_similarity_search( lru_vector_store: Optional[LRUVectorStore], search_text: str, ) -> str: - from langchain.vectorstores import FAISS - from langchain.embeddings import HuggingFaceBgeEmbeddings + try: + from langchain.vectorstores import FAISS + from langchain.embeddings import HuggingFaceBgeEmbeddings
Is this the same as ["faiss-cpu", "sentence-transformers", "torch"]?
pyspark-ai
github_2023
python
162
pyspark-ai
gengliangwang
@@ -351,6 +351,16 @@ def create_df( :return: a Spark DataFrame """ + # check for necessary dependencies + try: + import requests + import tiktoken + from bs4 import BeautifulSoup + except ImportError: + raise Exception( + "Dependencies for `create_df` not found. To fix, run `pip install pyspark-ai[create]`"
create => ingestion
pyspark-ai
github_2023
others
162
pyspark-ai
gengliangwang
@@ -14,10 +14,26 @@ For a more comprehensive introduction and background to our project, we have the ## Installation +pyspark-ai can be installed via pip from [PyPI](https://pypi.org/project/pyspark-ai/): ```bash pip install pyspark-ai ``` +pyspark-ai can also be installed with optional dependencies to enable certain functionality. +For example, to install pyspark-ai with the optional dependencies to ingest data into a DataFrame: + +```bash +pip install "pyspark-ai[ingestion]"
Let's mention plot instead since it is much more popular.
pyspark-ai
github_2023
others
162
pyspark-ai
gengliangwang
@@ -91,6 +107,27 @@ df.ai.transform("Pivot the data by product and the revenue for each product").sh For a detailed walkthrough of the transformations, please refer to our [transform_dataframe.ipynb](https://github.com/databrickslabs/pyspark-ai/blob/master/examples/transform_dataframe.ipynb) notebook. +### Transform Accuracy Improvement: Vector Similarity Search + +To improve the accuracy of transform query generation, you can also optionally enable vector similarity search. +This is done by specifying a `vector_store_dir` location for the vector files when you initialize SparkAI. For example: + +```python +from langchain.chat_models import AzureChatOpenAI +from pyspark_ai import SparkAI + +llm = AzureChatOpenAI(
Let's ignore the details of LLM here.
pyspark-ai
github_2023
others
162
pyspark-ai
gengliangwang
@@ -91,6 +107,27 @@ df.ai.transform("Pivot the data by product and the revenue for each product").sh For a detailed walkthrough of the transformations, please refer to our [transform_dataframe.ipynb](https://github.com/databrickslabs/pyspark-ai/blob/master/examples/transform_dataframe.ipynb) notebook. +### Transform Accuracy Improvement: Vector Similarity Search + +To improve the accuracy of transform query generation, you can also optionally enable vector similarity search. +This is done by specifying a `vector_store_dir` location for the vector files when you initialize SparkAI. For example: + +```python +from langchain.chat_models import AzureChatOpenAI +from pyspark_ai import SparkAI + +llm = AzureChatOpenAI( + deployment_name=..., + model_name=... +) +spark_ai = SparkAI(vector_store_dir="temp/", llm=llm) # vector files will be stored in the temp dir
Let's ignore the llm parameter in this example since there is default value
pyspark-ai
github_2023
others
162
pyspark-ai
gengliangwang
@@ -1,15 +1,25 @@ -# Installation and setup +# Installation and Setup ## Installation +pyspark-ai can be installed via pip from [PyPI](https://pypi.org/project/pyspark-ai/): ```bash pip install pyspark-ai ``` +pyspark-ai can also be installed with optional dependencies to enable certain functionality. +For example, to install pyspark-ai with the optional dependencies to ingest data into a DataFrame: + +```bash +pip install "pyspark-ai[ingestion]"
Again, let's mention plot instead.
pyspark-ai
github_2023
python
160
pyspark-ai
gengliangwang
@@ -125,7 +125,10 @@ def __init__(self, vector_file_dir: str, max_size: float = 16) -> None: self.files[file_path] = file_size self.current_size += file_size else: - shutil.rmtree(file_path) + if os.path.isfile(file_path): + os.remove(file_path)
How about just throwing an error and letting the user manually clean it up or increase the size limit? When Spark creates table from a dir, it also throw exception instead of deleting files, in case of mistakes.
pyspark-ai
github_2023
python
160
pyspark-ai
gengliangwang
@@ -106,36 +106,40 @@ async def _arun(self, *args: Any, **kwargs: Any) -> Any: class LRUVectorStore: """Implements an LRU policy to enforce a max storage space for vector file storage.""" - def __init__(self, vector_file_dir: str, max_size: float = 16) -> None: + def __init__(self, vector_store_dir: str, max_size: float = 16) -> None: # by default, max_size = 16 GB self.files: OrderedDict[str, float] = OrderedDict() - self.vector_file_dir = vector_file_dir + self.vector_store_dir = vector_store_dir # represent in bytes to prevent floating point errors self.max_bytes = max_size * 1e9 self.current_size = 0 - # initialize the file cache, if vector_file_dir exists + # initialize the file cache, if vector_store_dir exists # existing files will get evicted in reverse-alphabetical order # TODO: write LRU to disk, to evict existing files in LRU order - if os.path.exists(self.vector_file_dir): - for file in os.listdir(self.vector_file_dir): - file_path = os.path.join(self.vector_file_dir, file) + if os.path.exists(self.vector_store_dir): + for file in os.listdir(self.vector_store_dir): + file_path = os.path.join(self.vector_store_dir, file) file_size = LRUVectorStore.get_file_size_bytes(file_path) if LRUVectorStore.get_file_size_bytes(file_path) <= self.max_bytes:
We can simply check whether self.current_size exceeds the limitation when the loop ends
pyspark-ai
github_2023
others
165
pyspark-ai
gengliangwang
@@ -0,0 +1,420 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Vector Similarity Search" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This notebook demonstrates usage of the vector similarity search, to help the agent select an exact query value." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "import warnings\n", + "warnings.filterwarnings('ignore')"
Why do we need this? Are there warning from Langchain?
pyspark-ai
github_2023
others
165
pyspark-ai
gengliangwang
@@ -0,0 +1,420 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Vector Similarity Search" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This notebook demonstrates usage of the vector similarity search, to help the agent select an exact query value." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "import warnings\n", + "warnings.filterwarnings('ignore')" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": false, + "jupyter": { + "outputs_hidden": false + } + }, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "Setting default log level to \"WARN\".\n", + "To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel).\n", + "23/10/16 20:31:02 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable\n" + ] + } + ], + "source": [ + "from pyspark_ai import SparkAI\n", + "\n", + "# enable vector similarity search by specifying a vector_store_dir location\n", + "spark_ai = SparkAI(enable_cache=False, vector_store_dir=\"temp/\", verbose=True)\n", + "spark_ai.activate()" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "# create a dataframe\n", + "countries_df = spark_ai._spark.createDataFrame(\n", + " [\n", + " (\"USA\", \"21.43 trillion USD\", 2.7, \"331 million\", 0.7, \"9.8 million sq km\"),\n", + " (\"CHN\", \"14.34 trillion USD\", 7.0, \"1.4 billion\", 0.4, \"9.6 million sq km\"),\n", + " (\"IND\", \"2.87 trillion USD\", 8.0, \"1.3 billion\", 1.2, \"3.3 million sq km\"),\n", + " (\"BRA\", \"1.87 trillion USD\", -3.5, \"211 million\", 0.7, \"8.5 million sq km\"),\n", + " (\"CAN\", \"1.64 trillion USD\", 0.7, \"38 million\", 0.8, \"9.98 million sq km\"),\n", + " (\"AUS\", \"1.37 trillion USD\", 1.0, \"25 million\", 1.1, \"7.7 million sq km\"),\n", + " (\"RUS\", \"1.47 trillion USD\", -2.0, \"144 million\", 0.04, \"17.1 million sq km\"),\n", + " (\"FRA\", \"2.71 trillion USD\", 1.3, \"67 million\", 0.3, \"551,695 sq km\"),\n", + " (\"GER\", \"3.68 trillion USD\", 0.8, \"83 million\", 0.2, \"357,022 sq km\"),\n", + " (\"JPN\", \"5.08 trillion USD\", 1.6, \"126 million\", 0.2, \"377,975 sq km\"),\n", + " (\"GBR\", \"2.83 trillion USD\", 0.3, \"67 million\", 0.6, \"243,610 sq km\"),\n", + " (\"ZAF\", \"352 billion USD\", 1.2, \"60 million\", 1.2, \"1.2 million sq km\")\n", + " ],\n", + " [\"country\", \"gdp\", \"gdp growth (%)\", \"population\", \"population growth (%)\", \"surface area\"]\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\u001b[92mINFO: \u001b[0mCreating temp view for the transform:\n", + "df.createOrReplaceTempView(\u001b[33m\"\u001b[39;49;00m\u001b[33mspark_ai_temp_view_352693026\u001b[39;49;00m\u001b[33m\"\u001b[39;49;00m)\u001b[37m\u001b[39;49;00m\n", + "\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + " \r" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "\n", + "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n", + "\u001b[32;1m\u001b[1;3mThought: The keyword '300,000,000' is most similar to the sample values in the `population` column.\n", + "I need to filter on a value from the `population` column, so I will use the tool similar_value to help me choose my filter value.\n", + "Action: similar_value\n", + "Action Input: 300,000,000|population|spark_ai_temp_view_352693026\u001b[0m\n", + "Observation: \u001b[38;5;200m\u001b[1;3m331 million\u001b[0m\n", + "Thought:\u001b[32;1m\u001b[1;3mThe correct `population` filter should be '331 million' because it is semantically closest to the keyword.\n", + "I will use the column `population` to filter the rows where its value is '331 million' and then select the `gdp` \n", + "because the question asks for the GDP of the country.\n", + "Action: query_validation\n", + "Action Input: SELECT `gdp` FROM `spark_ai_temp_view_352693026` WHERE `population` = '331 million'\u001b[0m\n", + "Observation: \u001b[33;1m\u001b[1;3mOK\u001b[0m\n", + "Thought:\u001b[32;1m\u001b[1;3mI now know the final answer.\n", + "Final Answer: SELECT `gdp` FROM `spark_ai_temp_view_352693026` WHERE `population` = '331 million'\u001b[0m\n", + "\n", + "\u001b[1m> Finished chain.\u001b[0m\n", + "+------------------+\n", + "| gdp|\n", + "+------------------+\n", + "|21.43 trillion USD|\n", + "+------------------+\n", + "\n" + ] + } + ], + "source": [ + "countries_df.ai.transform(desc=\"What is the GDP of the country that has around 300,000,000 people?\", cache=False).show()"
Note: the fair sql should be filtering population in a range, such as `population` > 270 million and `population` < 330 million. so this is actually not a good example. Is there another good dataset or question? If not, let's drop this one.
pyspark-ai
github_2023
python
159
pyspark-ai
xinrong-meng
@@ -227,31 +227,25 @@ ) PLOT_PROMPT_TEMPLATE = """ -You are an Apache Spark SQL expert programmer. -It is forbidden to include old deprecated APIs in your code. -For example, you will not use the pandas method "append" because it is deprecated. - Given a pyspark DataFrame `df`, with the output columns: {columns} -And an explanation of `df`: {explain} - -Write Python code to visualize the result of `df` using plotly. Do any aggregation against `df` -first, before converting the `df` to a pandas DataFrame. Make sure to use the exact column names -of `df`. -Your code may NOT contain "append" anywhere. Instead of append, use pd.concat. -There is no need to install any package with pip. Do include any necessary import statements. -Display the plot directly, instead of saving into an HTML. -Do not use scatter plot to display any kind of percentage data. -You must import and start your Spark session if you use a Spark DataFrame. -Remember to ensure that your code does NOT include "append" anywhere, under any circumstance (use pd.concat instead). +Write Python code to visualize the result of `df` using plotly: +1. Do any aggregation against `df` first, before converting the `df` to a pandas DataFrame. +2. Make sure to use the exact column names of `df`. +3. Your code may NOT contain "append" anywhere. Instead of append, use pd.concat. +4. There is no need to install any package with pip. Do include any necessary import statements. +5. Display the plot directly, instead of saving into an HTML. +6. Do not use scatter plot to display any kind of percentage data.
May I ask what's the reason for 6.?
pyspark-ai
github_2023
others
159
pyspark-ai
xinrong-meng
@@ -0,0 +1,179 @@ +start_lat,start_lon,end_lat,end_lon,airline,airport1,airport2,cnt
I'm wondering why we don't pull the data from the original website but copy the file.
pyspark-ai
github_2023
python
159
pyspark-ai
xinrong-meng
@@ -0,0 +1,91 @@ +from typing import Any, List, Optional + +from langchain import LLMChain +from langchain.callbacks.manager import Callbacks +from langchain.chat_models.base import BaseChatModel +from langchain.schema import BaseMessage, HumanMessage +from pyspark.sql import DataFrame + +from pyspark_ai.code_logger import CodeLogger + +from pyspark_ai.ai_utils import AIUtils + +from pyspark_ai.cache import Cache +from pyspark_ai.temp_view_utils import canonize_string + +SKIP_CACHE_TAGS = ["SKIP_CACHE"] + + +class PythonExecutor(LLMChain): + """LLM Chain to generate python code. It supports caching and retrying.""" + + df: DataFrame + cache: Cache = None + logger: CodeLogger + max_retries: int = 3 + + def run( + self, + *args: Any, + callbacks: Callbacks = None, + tags: Optional[List[str]] = None, + **kwargs: Any, + ) -> str: + assert not args, "The chain expected no arguments" + # assert llm is an instance of BaseChatModel + assert isinstance( + self.llm, BaseChatModel + ), "The llm is not an instance of BaseChatModel" + prompt_str = canonize_string(self.prompt.format_prompt(**kwargs).to_string()) + use_cache = tags != SKIP_CACHE_TAGS + if self.cache is not None: + cached_result = self.cache.lookup(prompt_str) if use_cache else None + if cached_result is not None: + self._execute_code(self.df, cached_result) + return cached_result + messages = [HumanMessage(content=prompt_str)] + response = self._generate_python_with_retries( + self.df, self.llm, messages, self.max_retries + ) + if use_cache and self.cache is not None: + self.cache.update(prompt_str, response) + return response + + @staticmethod + def _execute_code(df: DataFrame, code: str): + import pandas as pd # noqa: F401
I'm wondering what's that used for
pyspark-ai
github_2023
python
159
pyspark-ai
xinrong-meng
@@ -0,0 +1,91 @@ +from typing import Any, List, Optional + +from langchain import LLMChain +from langchain.callbacks.manager import Callbacks +from langchain.chat_models.base import BaseChatModel +from langchain.schema import BaseMessage, HumanMessage +from pyspark.sql import DataFrame + +from pyspark_ai.code_logger import CodeLogger + +from pyspark_ai.ai_utils import AIUtils + +from pyspark_ai.cache import Cache +from pyspark_ai.temp_view_utils import canonize_string + +SKIP_CACHE_TAGS = ["SKIP_CACHE"] + + +class PythonExecutor(LLMChain): + """LLM Chain to generate python code. It supports caching and retrying.""" + + df: DataFrame + cache: Cache = None + logger: CodeLogger + max_retries: int = 3 + + def run( + self, + *args: Any, + callbacks: Callbacks = None, + tags: Optional[List[str]] = None, + **kwargs: Any, + ) -> str: + assert not args, "The chain expected no arguments" + # assert llm is an instance of BaseChatModel + assert isinstance( + self.llm, BaseChatModel + ), "The llm is not an instance of BaseChatModel" + prompt_str = canonize_string(self.prompt.format_prompt(**kwargs).to_string()) + use_cache = tags != SKIP_CACHE_TAGS + if self.cache is not None: + cached_result = self.cache.lookup(prompt_str) if use_cache else None + if cached_result is not None: + self._execute_code(self.df, cached_result) + return cached_result + messages = [HumanMessage(content=prompt_str)] + response = self._generate_python_with_retries( + self.df, self.llm, messages, self.max_retries + ) + if use_cache and self.cache is not None: + self.cache.update(prompt_str, response) + return response + + @staticmethod + def _execute_code(df: DataFrame, code: str): + import pandas as pd # noqa: F401 + + exec(compile(code, "plot_df-CodeGen", "exec")) + + def _generate_python_with_retries( + self, + df: DataFrame, + chat_model: BaseChatModel, + messages: List[BaseMessage], + retries: int = 3, + ) -> str: + response = chat_model.predict_messages(messages) + if self.logger is not None: + self.logger.info(response.content) + code = "\n".join(AIUtils.extract_code_blocks(response.content)) + try: + self._execute_code(df, code) + return code + except Exception as e: + if self.logger is not None: + self.logger.warning("Getting the following error: \n" + str(e)) + if retries <= 0: + # if we have no more retries, raise the exception + self.logger.info( + "No more retries left, please modify the instruction or modify the generated code" + ) + return ""
Do we want to raise an exception here instead?
pyspark-ai
github_2023
python
157
pyspark-ai
gengliangwang
@@ -60,6 +61,7 @@ def __init__( cache_file_format: str = "json", cache_file_location: Optional[str] = None, vector_store_dir: Optional[str] = None, + vector_store_max_size: Optional[float] = 1e6,
Shall we make it an Int? What's the unit here, KB?
pyspark-ai
github_2023
python
157
pyspark-ai
gengliangwang
@@ -101,12 +103,49 @@ async def _arun(self, *args: Any, **kwargs: Any) -> Any: raise NotImplementedError("ListTablesSqlDbTool does not support async") +class LRUVectorStore: + """Implements an LRU policy to enforce a max storage space for vector file storage.""" + + def __init__(self, vector_file_dir: str, max_size: float = 1e6): + # by default, max_size = 1e6 bytes
1M is just too small
pyspark-ai
github_2023
python
157
pyspark-ai
gengliangwang
@@ -101,12 +103,49 @@ async def _arun(self, *args: Any, **kwargs: Any) -> Any: raise NotImplementedError("ListTablesSqlDbTool does not support async") +class LRUVectorStore: + """Implements an LRU policy to enforce a max storage space for vector file storage.""" + + def __init__(self, vector_file_dir: str, max_size: float = 1e6): + # by default, max_size = 1e6 bytes + self.cache = OrderedDict()
We need to load the existing index files under the file path into the OrderedDict. The files under vector_file_dir can be reused after restarting PySparkAI. (You can also refer some of the code from https://chat.openai.com/share/2bd66613-5dc1-427e-9277-fb45b317438a)
pyspark-ai
github_2023
python
157
pyspark-ai
gengliangwang
@@ -150,6 +168,51 @@ def test_similar_value_tool_e2e(self): finally: self.spark.sql(f"DROP TABLE IF EXISTS {table_name}") + def test_vector_file_lru_cache_max_files(self): + """Tests VectorFileLRUCache adheres to max file size, using WikiSQL training tables""" + # set max vector files to 5e4 + vector_store_max_size = 5e4 + + spark_ai = SparkAI( + llm=self.llm_mock, + spark_session=self.spark, + vector_store_dir=self.vector_store_dir, + vector_store_max_size=vector_store_max_size, + ) + agent = spark_ai._create_sql_agent() + similar_value_tool = agent.lookup_tool("similar_value") + + table_file = "tests/data/test_transform_ai_tools.tables.jsonl" + source_file = "tests/data/test_similar_value_tool_e2e.jsonl" + + # prepare tables + statements = create_temp_view_statements(table_file) + for stmt in statements: + self.spark.sql(stmt) + + ( + tables, + tool_inputs, + expected_results, + ) = TestSimilarValueTool.get_expected_results(source_file) + + for table, tool_input, expected_result in zip( + tables, tool_inputs, expected_results + ): + table_name = get_table_name(table) + try: + df = self.spark.table(f"`{table_name}`") + df.createOrReplaceTempView(f"`{table_name}`") + similar_value_tool.run(f"{tool_input}{table_name}") + + # test that number of vector files stored on disk never exceeds vector_store_max_size + self.assertTrue( + LRUVectorStore.get_storage(self.vector_store_dir) + <= vector_store_max_size
shall we make vector_store_max_size smaller and check if there is a file/files evicted?
pyspark-ai
github_2023
python
157
pyspark-ai
gengliangwang
@@ -60,6 +61,7 @@ def __init__( cache_file_format: str = "json", cache_file_location: Optional[str] = None, vector_store_dir: Optional[str] = None, + vector_store_max_gb: Optional[float] = 1e6,
1000000GB is too big. Let's make it 16GB by default.
pyspark-ai
github_2023
python
157
pyspark-ai
gengliangwang
@@ -101,13 +103,70 @@ async def _arun(self, *args: Any, **kwargs: Any) -> Any: raise NotImplementedError("ListTablesSqlDbTool does not support async") +class LRUVectorStore: + """Implements an LRU policy to enforce a max storage space for vector file storage.""" + + def __init__(self, vector_file_dir: str, max_size: float = 1e6) -> None: + # by default, max_size = 1e6 GB + self.files: OrderedDict[str, float] = OrderedDict() + self.vector_file_dir = vector_file_dir + # represent in bytes to prevent floating point errors + self.max_bytes = max_size * 1e9 + self.current_size = 0 + + # initialize the file cache, if vector_file_dir exists + # existing files will get evicted in reverse-alphabetical order + # TODO: write LRU to disk, to evict existing files in LRU order + if os.path.exists(self.vector_file_dir): + for file in os.listdir(self.vector_file_dir): + file_full_path = os.path.join(self.vector_file_dir, file) + file_size = os.path.getsize(file_full_path)
we should either use `os.path.getsize` in all the code, or all use `LRUVectorStore.get_file_size_gb` in all the code.
pyspark-ai
github_2023
python
157
pyspark-ai
gengliangwang
@@ -101,13 +103,70 @@ async def _arun(self, *args: Any, **kwargs: Any) -> Any: raise NotImplementedError("ListTablesSqlDbTool does not support async") +class LRUVectorStore: + """Implements an LRU policy to enforce a max storage space for vector file storage.""" + + def __init__(self, vector_file_dir: str, max_size: float = 1e6) -> None: + # by default, max_size = 1e6 GB + self.files: OrderedDict[str, float] = OrderedDict() + self.vector_file_dir = vector_file_dir + # represent in bytes to prevent floating point errors + self.max_bytes = max_size * 1e9 + self.current_size = 0 + + # initialize the file cache, if vector_file_dir exists + # existing files will get evicted in reverse-alphabetical order + # TODO: write LRU to disk, to evict existing files in LRU order + if os.path.exists(self.vector_file_dir): + for file in os.listdir(self.vector_file_dir): + file_full_path = os.path.join(self.vector_file_dir, file) + file_size = os.path.getsize(file_full_path) + self.current_size += file_size + self.files[file_full_path] = file_size + + @staticmethod + def get_file_size_gb(file_path: str) -> float: + return os.path.getsize(file_path)
Does this returns GB?
pyspark-ai
github_2023
python
157
pyspark-ai
gengliangwang
@@ -150,6 +168,144 @@ def test_similar_value_tool_e2e(self): finally: self.spark.sql(f"DROP TABLE IF EXISTS {table_name}") + def test_vector_file_lru_store_large_max_files(self): + """Tests LRUVectorStore stores all vector files to disk with large max size, for 3 small dfs""" + vector_store_max_gb = 5e6 + + spark_ai = SparkAI( + llm=self.llm_mock, + spark_session=self.spark, + vector_store_dir=self.vector_store_dir, + vector_store_max_gb=vector_store_max_gb, + ) + agent = spark_ai._create_sql_agent() + similar_value_tool = agent.lookup_tool("similar_value") + + table_file = "tests/data/test_transform_ai_tools.tables.jsonl" + source_file = "tests/data/test_similar_value_tool_e2e.jsonl" + + # prepare tables + statements = create_temp_view_statements(table_file) + for stmt in statements: + self.spark.sql(stmt) + + ( + tables, + tool_inputs, + expected_results, + ) = TestSimilarValueTool.get_expected_results(source_file) + + for table, tool_input, expected_result in zip( + tables, tool_inputs, expected_results + ): + table_name = get_table_name(table) + try: + df = self.spark.table(f"`{table_name}`") + df.createOrReplaceTempView(f"`{table_name}`") + similar_value_tool.run(f"{tool_input}{table_name}") + finally: + self.spark.sql(f"DROP TABLE IF EXISTS {table_name}") + + # test that all 3 vector files stored on disk + self.assertTrue(len(os.listdir(self.vector_store_dir)) == 3) + + def test_vector_file_lru_store_zero_max_files(self): + """Tests LRUVectorStore always evicts files when max dir size is 0""" + vector_store_max_gb = 0 + + spark_ai = SparkAI( + llm=self.llm_mock, + spark_session=self.spark, + vector_store_dir=self.vector_store_dir, + vector_store_max_gb=vector_store_max_gb, + ) + agent = spark_ai._create_sql_agent() + similar_value_tool = agent.lookup_tool("similar_value") + + table_file = "tests/data/test_transform_ai_tools.tables.jsonl" + source_file = "tests/data/test_similar_value_tool_e2e.jsonl" + + # prepare tables + statements = create_temp_view_statements(table_file) + for stmt in statements: + self.spark.sql(stmt) + + ( + tables, + tool_inputs, + expected_results, + ) = TestSimilarValueTool.get_expected_results(source_file) + + for table, tool_input, expected_result in zip( + tables, tool_inputs, expected_results + ): + table_name = get_table_name(table) + try: + df = self.spark.table(f"`{table_name}`") + df.createOrReplaceTempView(f"`{table_name}`") + similar_value_tool.run(f"{tool_input}{table_name}") + + # test that number of vector files stored on disk never exceeds vector_store_max_gb, 0 + self.assertTrue(len(os.listdir(self.vector_store_dir)) == 0) + self.assertTrue(LRUVectorStore.get_storage(self.vector_store_dir) == 0) + finally: + self.spark.sql(f"DROP TABLE IF EXISTS {table_name}") + + def test_vector_file_lru_store_prepopulated_files(self):
nit: let mock method get_file_size_gb and make it always return 1. Then we can test maximum 2GB limit and creating 3 files, the first created file should be evicted.
pyspark-ai
github_2023
python
157
pyspark-ai
gengliangwang
@@ -101,13 +103,70 @@ async def _arun(self, *args: Any, **kwargs: Any) -> Any: raise NotImplementedError("ListTablesSqlDbTool does not support async") +class LRUVectorStore: + """Implements an LRU policy to enforce a max storage space for vector file storage.""" + + def __init__(self, vector_file_dir: str, max_size: float = 16) -> None: + # by default, max_size = 16 GB + self.files: OrderedDict[str, float] = OrderedDict() + self.vector_file_dir = vector_file_dir + # represent in bytes to prevent floating point errors + self.max_bytes = max_size * 1e9 + self.current_size = 0 + + # initialize the file cache, if vector_file_dir exists + # existing files will get evicted in reverse-alphabetical order + # TODO: write LRU to disk, to evict existing files in LRU order + if os.path.exists(self.vector_file_dir): + for file in os.listdir(self.vector_file_dir): + file_full_path = os.path.join(self.vector_file_dir, file) + file_size = LRUVectorStore.get_file_size_bytes(file_full_path) + self.current_size += file_size + self.files[file_full_path] = file_size + + @staticmethod + def get_file_size_bytes(file_path: str) -> float: + return os.path.getsize(file_path) + + @staticmethod + def get_storage(vector_file_dir: str) -> float: + # calculate current storage space of vector files, in bytes + size = 0 + for path, dirs, files in os.walk(vector_file_dir): + for f in files: + fp = os.path.join(path, f) + size += LRUVectorStore.get_file_size_bytes(fp) + return size + + def access(self, file_path: str) -> None: + # move accessed key to end of LRU cache + if file_path in self.files: + self.files.move_to_end(file_path) + + def add(self, file_path: str) -> None: + # remove file path if max storage size exceeded, else add + curr_file_size = LRUVectorStore.get_file_size_bytes(file_path)
What if curr_file_size is larger than the max size limit? It will be added to the store and then everything will be deleted..
pyspark-ai
github_2023
python
156
pyspark-ai
gengliangwang
@@ -133,6 +135,8 @@ def get_tables_and_questions(source_file): errors = 0 # Create sql query for each question and table + error_file = open("data/error_file.txt", "w")
let's make it `mismatched_results.txt`.
pyspark-ai
github_2023
python
156
pyspark-ai
gengliangwang
@@ -87,7 +87,7 @@ Observation: 01-01-2006 Thought: The correct Birthday filter should be '01-01-2006' because it is semantically closest to the keyword. I will use the column 'Birthday' to filter the rows where its value is '01-01-2006' and then select the COUNT(`Student`) -because COUNT gives me the total number of students. +because the question asks for the total number of students.
QQ: does this fix all mismatched all `COUNT` queries?
pyspark-ai
github_2023
python
155
pyspark-ai
gengliangwang
@@ -51,6 +51,7 @@ Write a Spark SQL query to retrieve from view `spark_ai_temp_view_14kjd0`: Find the mountain located in Japan. Thought: The column names are non-descriptive, but from the sample values I see that column `a` contains mountains and column `c` contains countries. So, I will filter on column `c` for 'Japan' and column `a` for the mountain. +I will use = rather than "like" in my SQL query because I need an exact match.
end-to-end test for this one?
pyspark-ai
github_2023
python
155
pyspark-ai
gengliangwang
@@ -123,12 +123,12 @@ def test_similar_value_tool_e2e(self): agent = spark_ai._create_sql_agent() similar_value_tool = agent.lookup_tool("similar_value") - table_file = "tests/data/test_similar_value_tool_e2e.tables.jsonl" + table_file = "tests/data/test_transform.tables.jsonl" source_file = "tests/data/test_similar_value_tool_e2e.jsonl" # prepare tables statements = create_temp_view_statements(table_file) - for stmt in statements: + for stmt in statements[:3]:
This is too hacky. It's ok to have two jsonl files, one for test_ai_tools and another one for end_to_end tests. This way, our tests are easier to understand.
pyspark-ai
github_2023
python
155
pyspark-ai
gengliangwang
@@ -135,6 +138,27 @@ def test_transform_col_query_wikisql(self): finally: self.spark.sql(f"DROP TABLE IF EXISTS {table_name}") + def test_filter_exact(self): + """Test that agent filters by an exact value""" + statements = create_temp_view_statements(
Nit: we can have a function get_table_name ``` def create_and_get_table(tbl: str): statements = create_temp_view_statements("tests/data/test_transform.tables.jsonl") tbl_in_json = "table_" + tbl.replaceAll("_", "-") for statement in statements: if tbl_in_json in statement: self.spark.sql(statement) return get_table_name(tbl) ``` So that we can reduce duplicated code and writing tests will be eaiser.
pyspark-ai
github_2023
python
155
pyspark-ai
gengliangwang
@@ -89,6 +89,19 @@ def setUp(self): schema="string", ) + def get_table_name(
let's rename this as create_and_get_table_name, since there is another function `get_table_name`
pyspark-ai
github_2023
python
153
pyspark-ai
gengliangwang
@@ -253,8 +253,10 @@ def _create_dataframe_with_llm( self._spark.sql(sql_query) return self._spark.table(view_name) - def _get_df_schema(self, df: DataFrame) -> str: - return "\n".join([f"{name}: {dtype}" for name, dtype in df.dtypes]) + def _get_df_schema(self, df: DataFrame) -> Tuple[list, str]:
let's split this into two methods. Returning two values here are confusing
pyspark-ai
github_2023
python
153
pyspark-ai
gengliangwang
@@ -41,20 +41,21 @@ ) SPARK_SQL_EXAMPLES = [ - """QUESTION: Given a Spark temp view `spark_ai_temp_view_14kjd0` with the following columns: + """QUESTION: Given a Spark temp view `spark_ai_temp_view_14kjd0` with the following sample vals,
nit: we can have a follow-up to create a function to unify the prompt over a table. So that both the example and the prompt for user input are consistent.
pyspark-ai
github_2023
python
153
pyspark-ai
gengliangwang
@@ -96,6 +96,34 @@ def test_dataframe_transform(self): transformed_df = df.ai.transform("what is the name with oldest age?") self.assertEqual(transformed_df.collect()[0][0], "Bob") + def test_transform_col_query_nondescriptive(self): + """Test that agent selects correct query column, even with non-descriptive column names, + by using sample column values""" + df = self.spark_ai._spark.createDataFrame( + [ + ("Shanghai", 31, "China"), + ("Seattle", 30, "United States"), + ("Austin", 33, "United States"), + ("Paris", 29, "France"), + ], + ["col1", "col2", "col3"], + ) + transformed_df = df.ai.transform("what city had the warmest temperature?") + self.assertEqual(transformed_df.collect()[0][0], "Austin") + + def test_transform_col_query_unintuitive(self):
This test case seems too much. I am not sure if it works with other LLMs in the future...
pyspark-ai
github_2023
others
145
pyspark-ai
gengliangwang
@@ -0,0 +1,875 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "2227e466-f9e4-4882-9a21-da2b1824b301", + "metadata": {}, + "source": [ + "# Generate Python UDFs for different cases" + ] + }, + { + "cell_type": "markdown", + "id": "86b69eae-351d-45f4-ac16-f3bd8eb2bd42", + "metadata": {}, + "source": [ + "## Initialization" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "1f1cc965-ed44-4a7b-9b37-7fd5a611d967", + "metadata": {}, + "outputs": [], + "source": [ + "# Suppress some deprecation warnings from langchain one may see on some platfroms\n", + "import warnings\n",
Hmmm, it doesn't seem necessary to have this cell in the example notebook, shall we remove it?
pyspark-ai
github_2023
others
145
pyspark-ai
gengliangwang
@@ -140,6 +140,9 @@ auto_top_growth_df.ai.verify("expect sales change percentage to be between -100 > result: True ### UDF Generation + +#### Example 1: Compute expression from columns
@SemyonSinchenko sorry but I would prefer keeping the README simple. > @SemyonSinchenko Again, thanks for working on this. Shall we also mention this new notebook in https://github.com/pyspark-ai/pyspark-ai/blob/master/docs/udf_generation.md? I meant to mention the new examples or notebook link in the `udf_generation.md`.
pyspark-ai
github_2023
others
145
pyspark-ai
gengliangwang
@@ -23,3 +25,117 @@ spark.sql("select brand as brand, previous_years_sales(brand, us_sales, sales_ch | Honda | 1315225| | Hyundai | 739045| +## Example 2: Parse heterogeneous JSON text + +```python +from typing import List + +@spark_ai.udf +def parse_heterogeneous_json(json_str: str, schema: List[str]) -> List[str]: + """Extract fields from heterogeneous JSON string based on given schema in a right order. + If field is missing replace it by None. All imports should be inside function.""" + ... +``` + +`df.show()`
Hi @SemyonSinchenko , the doc is now available at https://pyspark.ai/udf_generation/ Shall we show how `df` is created instead?
pyspark-ai
github_2023
others
144
pyspark-ai
gengliangwang
@@ -39,7 +39,6 @@ pyarrow = ">=4.0.0" grpcio-status = ">=1.56.0" faiss-cpu = "^1.7.4" sentence-transformers = "^2.2.2" -flagembedding = "^1.1.1" babel = "^2.12.1"
Can we remove babel & torch?
pyspark-ai
github_2023
python
141
pyspark-ai
gengliangwang
@@ -334,18 +360,146 @@ def test_spark_connect_pivot(self): ("C", "English", 90), ("C", "Science", 100), ], - ["Student", "Subject", "Marks"] + ["Student", "Subject", "Marks"], ) result = df.ai.transform("pivot using Subject for Marks") - expected_lst = [Row(Student='B', English=75, Maths=80, Science=None), - Row(Student='C', English=90, Maths=None, Science=100), - Row(Student='A', English=45, Maths=50, Science=None)] + expected_lst = [ + Row(Student="B", English=75, Maths=80, Science=None), + Row(Student="C", English=90, Maths=None, Science=100), + Row(Student="A", English=45, Maths=50, Science=None), + ] self.assertEqual(result.collect(), expected_lst) except Exception: self.fail("Spark Connect pivot error") +class UDFGenerationTest(SparkTestCase):
@SemyonSinchenko let's move this one to tests/test_end_to_end.py like https://github.com/pyspark-ai/pyspark-ai/pull/139 did
pyspark-ai
github_2023
python
141
pyspark-ai
gengliangwang
@@ -334,18 +360,146 @@ def test_spark_connect_pivot(self): ("C", "English", 90), ("C", "Science", 100), ], - ["Student", "Subject", "Marks"] + ["Student", "Subject", "Marks"], ) result = df.ai.transform("pivot using Subject for Marks") - expected_lst = [Row(Student='B', English=75, Maths=80, Science=None), - Row(Student='C', English=90, Maths=None, Science=100), - Row(Student='A', English=45, Maths=50, Science=None)] + expected_lst = [ + Row(Student="B", English=75, Maths=80, Science=None), + Row(Student="C", English=90, Maths=None, Science=100), + Row(Student="A", English=45, Maths=50, Science=None), + ] self.assertEqual(result.collect(), expected_lst) except Exception: self.fail("Spark Connect pivot error") +class UDFGenerationTest(SparkTestCase): + # end2end test + + def setUp(self): + self.spark_ai = SparkAI( + cache_file_location="examples/spark_ai_cache.json",
we don't need cache file in for end-to-end test. Previously we use cache file since we didn't setup the API key in github action.
pyspark-ai
github_2023
others
140
pyspark-ai
gengliangwang
@@ -40,6 +40,8 @@ grpcio-status = ">=1.56.0" faiss-cpu = "^1.7.4" sentence-transformers = "^2.2.2" flagembedding = "^1.1.1" +babel = "^2.12.1" +torch = ">=2.0.0, !=2.0.1"
why put more dependencies here? we should revisit all the dependency for SimilarValueTool and make our SDK more lightweight.
pyspark-ai
github_2023
python
140
pyspark-ai
gengliangwang
@@ -46,5 +57,91 @@ def test_include_similar_value_tool(self): ) +class TestSimilarValueTool(unittest.TestCase): + """Tests SimilarValueTool functionality""" + + @classmethod + def setUpClass(cls): + cls.spark = SparkSession.builder.getOrCreate() + cls.llm_mock = MagicMock(spec=BaseLanguageModel) + + def test_similar_dates(self): + """Test retrieval of similar date by similarity_vector_search""" + dates = [ + "2023-04-15", + "2022-09-28", + "2011-01-10", + "2022-11-05", + "2023-08-20", + "2019-07-12", + "2023-03-25", + "2002-05-30", + "2023-06-08", + "20007-12-03", + ] + + # try different formats of date "2023-03-25" + search_dates = [ + "March 25, 2023", + "March 25th", + "03/25/2023", + "03/25/23", + "3/25", + ] + + for search_date in search_dates: + similar_value = VectorSearchUtil.vector_similarity_search( + dates, None, search_date + ) + self.assertEqual(similar_value, "2023-03-25") + + def get_tool_lists(self, inputs_file): + """Helper util to get inputs for testing SimilarValueTool""" + import json + + tables = [] + inputs = [] + results = [] + + with open(inputs_file, "r") as f: + for line in f: + item = json.loads(line.strip()) + tables.append(item["table_id"]) + inputs.append(item["tool_input"]) + results.append(item["result"]) + + return tables, inputs, results + + def test_similar_value_tool_e2e(self): + """End-to-end tests of similar value tool, using WikiSQL training tables""" + spark_ai = SparkAI( + llm=self.llm_mock, + spark_session=self.spark, + vector_store_dir="tests/test/", + ) + agent = spark_ai._create_sql_agent() + similar_value_tool = agent.lookup_tool("similar_value") + + table_file = "tests/test/test_similar_value_tool_e2e.tables.jsonl" + source_file = "tests/test/test_similar_value_tool_e2e.jsonl" + + # prepare tables + statements = create_temp_view_statements(table_file) + spark = SparkSession.builder.getOrCreate() + for stmt in statements: + spark.sql(stmt)
Need to drop tables at the end
pyspark-ai
github_2023
python
140
pyspark-ai
gengliangwang
@@ -46,5 +57,91 @@ def test_include_similar_value_tool(self): ) +class TestSimilarValueTool(unittest.TestCase): + """Tests SimilarValueTool functionality""" + + @classmethod + def setUpClass(cls): + cls.spark = SparkSession.builder.getOrCreate() + cls.llm_mock = MagicMock(spec=BaseLanguageModel) + + def test_similar_dates(self): + """Test retrieval of similar date by similarity_vector_search""" + dates = [ + "2023-04-15", + "2022-09-28", + "2011-01-10", + "2022-11-05", + "2023-08-20", + "2019-07-12", + "2023-03-25", + "2002-05-30", + "2023-06-08", + "20007-12-03", + ] + + # try different formats of date "2023-03-25" + search_dates = [ + "March 25, 2023", + "March 25th", + "03/25/2023", + "03/25/23", + "3/25", + ] + + for search_date in search_dates: + similar_value = VectorSearchUtil.vector_similarity_search( + dates, None, search_date + ) + self.assertEqual(similar_value, "2023-03-25") + + def get_tool_lists(self, inputs_file):
get_expected_results?
pyspark-ai
github_2023
python
133
pyspark-ai
gengliangwang
@@ -126,13 +126,21 @@ def _create_llm_chain(self, prompt: BasePromptTemplate): return LLMChainWithCache(llm=self._llm, prompt=prompt, cache=self._cache) def _create_sql_agent(self): - tools = [ - QuerySparkSQLTool(spark=self._spark), - QueryValidationTool(spark=self._spark), - SimilarValueTool( - spark=self._spark, vector_store_dir=self._vector_store_dir - ), - ] + # exclude SimilarValueTool if vector_store_dir not configured + tools = ( + [ + QuerySparkSQLTool(spark=self._spark), + QueryValidationTool(spark=self._spark), + SimilarValueTool( + spark=self._spark, vector_store_dir=self._vector_store_dir + ), + ] + if self._vector_store_dir
let's have a simple test case for this, to verify the tools
pyspark-ai
github_2023
python
133
pyspark-ai
gengliangwang
@@ -0,0 +1,38 @@ +import unittest + +from pyspark_ai.pyspark_ai import SparkAI +from pyspark_ai.tool import QuerySparkSQLTool, QueryValidationTool, SimilarValueTool + + +class TestToolsInit(unittest.TestCase): + def test_exclude_similar_value_tool(self): + """Test that SimilarValueTool is excluded by default""" + spark_ai = SparkAI()
need to pass a mocked llm
pyspark-ai
github_2023
python
119
pyspark-ai
gengliangwang
@@ -123,6 +128,8 @@ def _create_sql_agent(self): tools = [ QuerySparkSQLTool(spark=self._spark), QueryValidationTool(spark=self._spark), + ColumnQueryTool(spark=self._spark), + SimilarValueTool(spark=self._spark, vector_store=None, stored_df_cols=set()),
Let's have a new variable `verctor_store_dir` in `SparkAI` which can be specified during init. And `verctor_store_dir` will be used when creating SimilarValueTool
pyspark-ai
github_2023
python
119
pyspark-ai
gengliangwang
@@ -104,3 +104,104 @@ def _run( async def _arun(self, *args: Any, **kwargs: Any) -> Any: raise NotImplementedError("ListTablesSqlDbTool does not support async") + + +class ColumnQueryTool(BaseTool): + """Tool for finding the correct column name given keywords from a question.""" + + spark: Union[SparkSession, ConnectSparkSession] = Field(exclude=True) + name = "get_column_name" + description = """ + This tool determines which column contains a keyword from the question. + Input to this tool is a str with a keyword of interest and a temp view name, output is the column name from the df + that contains the keyword. + Input should be pipe-separated, in the format: keyword|temp_view_name
Shall we specify `args_schema` and use two args in the _run method? Example: https://github.com/langchain-ai/langchain/blob/master/libs/langchain/langchain/tools/file_management/copy.py#L25
pyspark-ai
github_2023
python
119
pyspark-ai
gengliangwang
@@ -104,3 +104,104 @@ def _run( async def _arun(self, *args: Any, **kwargs: Any) -> Any: raise NotImplementedError("ListTablesSqlDbTool does not support async") + + +class ColumnQueryTool(BaseTool): + """Tool for finding the correct column name given keywords from a question.""" + + spark: Union[SparkSession, ConnectSparkSession] = Field(exclude=True) + name = "get_column_name" + description = """ + This tool determines which column contains a keyword from the question. + Input to this tool is a str with a keyword of interest and a temp view name, output is the column name from the df + that contains the keyword. + Input should be pipe-separated, in the format: keyword|temp_view_name + """ + + def _run( + self, input: str, run_manager: Optional[CallbackManagerForToolRun] = None + ) -> str: + input_lst = input.split("|") + + keyword = input_lst[0].lower() + temp_name = input_lst[1] + + # get columns + df = self.spark.sql("select * from {}".format(temp_name)) + col_lst = df.columns + + for col in col_lst: + result = self.spark.sql( + "select * from {} where `{}` like '%{}%'".format(
note: only string column supports 'like' operator
pyspark-ai
github_2023
python
119
pyspark-ai
gengliangwang
@@ -104,3 +104,104 @@ def _run( async def _arun(self, *args: Any, **kwargs: Any) -> Any: raise NotImplementedError("ListTablesSqlDbTool does not support async") + + +class ColumnQueryTool(BaseTool): + """Tool for finding the correct column name given keywords from a question.""" + + spark: Union[SparkSession, ConnectSparkSession] = Field(exclude=True) + name = "get_column_name" + description = """ + This tool determines which column contains a keyword from the question. + Input to this tool is a str with a keyword of interest and a temp view name, output is the column name from the df + that contains the keyword. + Input should be pipe-separated, in the format: keyword|temp_view_name + """ + + def _run( + self, input: str, run_manager: Optional[CallbackManagerForToolRun] = None + ) -> str: + input_lst = input.split("|") + + keyword = input_lst[0].lower() + temp_name = input_lst[1] + + # get columns + df = self.spark.sql("select * from {}".format(temp_name)) + col_lst = df.columns + + for col in col_lst: + result = self.spark.sql( + "select * from {} where `{}` like '%{}%'".format( + temp_name, col, keyword + ) + ) + + if len(result.collect()) != 0: + return col + + return "" + + async def _arun(self, *args: Any, **kwargs: Any) -> Any: + raise NotImplementedError("ColumnQueryTool does not support async") + + +class SimilarValueTool(BaseTool): + """Tool for running a Spark SQL query to rank the values in a column by similarity score to a keyword.""" + + spark: Union[SparkSession, ConnectSparkSession] = Field(exclude=True) + name = "similar_value" + description = """ + This tool finds the semantically closest word to a keyword from a vector database, using the FAISS library. + Input to this tool is a pipe-separated string in this format: keyword|column_name|temp_view_name. + The temp_view_name will be queried in the column_name for the semantically closest word to the keyword. + """ + + vector_store: Any + stored_df_cols: set + + def vector_similarity_search(self, search_text: str, col: str, temp_name: str): + from langchain.docstore.document import Document + from langchain.vectorstores import FAISS + from langchain.embeddings.openai import OpenAIEmbeddings + + new_df = self.spark.sql("select distinct {} from {}".format(col, temp_name)) + new_df_lst = [str(row[col]) for row in new_df.collect()] + + # Create documents from col data + if (temp_name, col) not in self.stored_df_cols: + documents = [] + + for val in new_df_lst: + document = Document(page_content=str(val), metadata={"temp_name": temp_name, "col_name": col}) + documents.append(document) + + if not self.vector_store: + self.vector_store = FAISS.from_documents(documents, OpenAIEmbeddings()) + else: + self.vector_store.add_documents(documents) + + self.stored_df_cols.add((temp_name, col)) + + docs = self.vector_store.similarity_search(search_text) + return docs[0].page_content + + def _run( + self, inputs: str, run_manager: Optional[CallbackManagerForToolRun] = None + ) -> str: + input_lst = inputs.split("|")
Same as the comment in https://github.com/databrickslabs/pyspark-ai/pull/119/files#r1333630340
pyspark-ai
github_2023
python
119
pyspark-ai
gengliangwang
@@ -104,3 +104,104 @@ def _run( async def _arun(self, *args: Any, **kwargs: Any) -> Any: raise NotImplementedError("ListTablesSqlDbTool does not support async") + + +class ColumnQueryTool(BaseTool):
I would suggest let's keep it simpler and add tool SimilarValueTool only in this PR
pyspark-ai
github_2023
python
119
pyspark-ai
gengliangwang
@@ -99,6 +104,7 @@ def __init__( ).search else: self._cache = None + self._vector_store_dir = vector_store_dir
We need to have a default value for the `vector_store_dir`. For example, "spark_ai_vector_store" under the temp dir of the file system.
pyspark-ai
github_2023
python
119
pyspark-ai
gengliangwang
@@ -104,3 +104,58 @@ def _run( async def _arun(self, *args: Any, **kwargs: Any) -> Any: raise NotImplementedError("ListTablesSqlDbTool does not support async") + + +class SimilarValueTool(BaseTool): + """Tool for finding the semantically closest word to a keyword from a vector database.""" + + spark: Union[SparkSession, ConnectSparkSession] = Field(exclude=True) + name = "similar_value" + description = """ + This tool finds the semantically closest word to a keyword from a vector database, using the FAISS library. + Input to this tool is a pipe-separated string in this format: keyword|column_name|temp_view_name. + The temp_view_name will be queried in the column_name for the semantically closest word to the keyword. + """ + + vector_store_dir: Optional[str] + + def vector_similarity_search(self, search_text: str, col: str, temp_name: str):
Let's move this one to a new class "VectorSearchUtil" as a static method
pyspark-ai
github_2023
others
119
pyspark-ai
gengliangwang
@@ -37,6 +37,11 @@ grpcio = ">=1.56.0" plotly = "^5.15.0" pyarrow = ">=4.0.0" grpcio-status = ">=1.56.0" +lib = "^4.0.0"
what is this about?
pyspark-ai
github_2023
python
119
pyspark-ai
gengliangwang
@@ -104,3 +104,73 @@ def _run( async def _arun(self, *args: Any, **kwargs: Any) -> Any: raise NotImplementedError("ListTablesSqlDbTool does not support async") + + +class VectorSearchUtil: + @staticmethod + def vector_similarity_search( + col_lst: list, + vector_store_path: Optional[str], + search_text: str, + col: str, + temp_name: str, + ): + from langchain.vectorstores import FAISS + from langchain.embeddings import HuggingFaceBgeEmbeddings + import os + + if vector_store_path and os.path.exists(vector_store_path): + vector_db = FAISS.load_local(vector_store_path, HuggingFaceBgeEmbeddings()) + else: + vector_db = FAISS.from_texts(col_lst, HuggingFaceBgeEmbeddings()) + + if vector_store_path: + vector_db.save_local(vector_store_path) + + docs = vector_db.similarity_search(search_text) + return docs[0].page_content + + +class SimilarValueTool(BaseTool): + """Tool for finding the semantically closest word to a keyword from a vector database.""" + + spark: Union[SparkSession, ConnectSparkSession] = Field(exclude=True) + name = "similar_value" + description = """ + This tool finds the semantically closest word to a keyword from a vector database, using the FAISS library. + Input to this tool is a pipe-separated string in this format: keyword|column_name|temp_view_name. + The temp_view_name will be queried in the column_name for the semantically closest word to the keyword. + """ + + vector_store_dir: Optional[str] + + def _run( + self, inputs: str, run_manager: Optional[CallbackManagerForToolRun] = None + ) -> str: + input_lst = inputs.split("|") + + search_text = input_lst[0] + col = input_lst[1] + temp_name = input_lst[2] + + new_df = self.spark.sql("select distinct `{}` from {}".format(col, temp_name))
If the vector store already exists, we don't need to run this query
pyspark-ai
github_2023
python
119
pyspark-ai
gengliangwang
@@ -104,3 +104,73 @@ def _run( async def _arun(self, *args: Any, **kwargs: Any) -> Any: raise NotImplementedError("ListTablesSqlDbTool does not support async") + + +class VectorSearchUtil: + @staticmethod + def vector_similarity_search( + col_lst: list, + vector_store_path: Optional[str], + search_text: str, + col: str, + temp_name: str, + ): + from langchain.vectorstores import FAISS + from langchain.embeddings import HuggingFaceBgeEmbeddings + import os + + if vector_store_path and os.path.exists(vector_store_path): + vector_db = FAISS.load_local(vector_store_path, HuggingFaceBgeEmbeddings()) + else: + vector_db = FAISS.from_texts(col_lst, HuggingFaceBgeEmbeddings()) + + if vector_store_path: + vector_db.save_local(vector_store_path) + + docs = vector_db.similarity_search(search_text) + return docs[0].page_content + + +class SimilarValueTool(BaseTool): + """Tool for finding the semantically closest word to a keyword from a vector database."""
I am not sure if we should make it more specific here by saying: Tool for finding the column value which is closet to the input text.
pyspark-ai
github_2023
python
119
pyspark-ai
gengliangwang
@@ -104,3 +104,73 @@ def _run( async def _arun(self, *args: Any, **kwargs: Any) -> Any: raise NotImplementedError("ListTablesSqlDbTool does not support async") + + +class VectorSearchUtil: + @staticmethod + def vector_similarity_search( + col_lst: list, + vector_store_path: Optional[str], + search_text: str, + col: str, + temp_name: str, + ): + from langchain.vectorstores import FAISS + from langchain.embeddings import HuggingFaceBgeEmbeddings + import os + + if vector_store_path and os.path.exists(vector_store_path): + vector_db = FAISS.load_local(vector_store_path, HuggingFaceBgeEmbeddings()) + else: + vector_db = FAISS.from_texts(col_lst, HuggingFaceBgeEmbeddings()) + + if vector_store_path: + vector_db.save_local(vector_store_path) + + docs = vector_db.similarity_search(search_text) + return docs[0].page_content + + +class SimilarValueTool(BaseTool): + """Tool for finding the semantically closest word to a keyword from a vector database.""" + + spark: Union[SparkSession, ConnectSparkSession] = Field(exclude=True) + name = "similar_value" + description = """ + This tool finds the semantically closest word to a keyword from a vector database, using the FAISS library.
Not sure if we need to mention FAISS to LLM. We should mention that there is an existing vector store which contains all the column values
pyspark-ai
github_2023
python
119
pyspark-ai
gengliangwang
@@ -104,3 +104,73 @@ def _run( async def _arun(self, *args: Any, **kwargs: Any) -> Any: raise NotImplementedError("ListTablesSqlDbTool does not support async") + + +class VectorSearchUtil: + @staticmethod + def vector_similarity_search( + col_lst: list, + vector_store_path: Optional[str], + search_text: str, + col: str, + temp_name: str, + ): + from langchain.vectorstores import FAISS + from langchain.embeddings import HuggingFaceBgeEmbeddings + import os + + if vector_store_path and os.path.exists(vector_store_path): + vector_db = FAISS.load_local(vector_store_path, HuggingFaceBgeEmbeddings()) + else: + vector_db = FAISS.from_texts(col_lst, HuggingFaceBgeEmbeddings()) + + if vector_store_path: + vector_db.save_local(vector_store_path) + + docs = vector_db.similarity_search(search_text) + return docs[0].page_content + + +class SimilarValueTool(BaseTool): + """Tool for finding the semantically closest word to a keyword from a vector database.""" + + spark: Union[SparkSession, ConnectSparkSession] = Field(exclude=True) + name = "similar_value" + description = """ + This tool finds the semantically closest word to a keyword from a vector database, using the FAISS library. + Input to this tool is a pipe-separated string in this format: keyword|column_name|temp_view_name. + The temp_view_name will be queried in the column_name for the semantically closest word to the keyword. + """ + + vector_store_dir: Optional[str] + + def _run( + self, inputs: str, run_manager: Optional[CallbackManagerForToolRun] = None + ) -> str: + input_lst = inputs.split("|") + + search_text = input_lst[0] + col = input_lst[1] + temp_name = input_lst[2] + + new_df = self.spark.sql("select distinct `{}` from {}".format(col, temp_name)) + col_lst = [str(row[col]) for row in new_df.collect()] + + vector_store_path = ( + (self.vector_store_dir + temp_name + "_" + col) + if self.vector_store_dir + else None + ) + + return VectorSearchUtil.vector_similarity_search( + col_lst, vector_store_path, search_text, col, temp_name + ) + + def _get_dataframe_results(self, df: DataFrame) -> list:
This is duplicated with the code in pyspark_ai.py...let's move them to a new file spark_utils.py
pyspark-ai
github_2023
python
119
pyspark-ai
gengliangwang
@@ -51,28 +64,49 @@ Write a Spark SQL query to retrieve from view `spark_ai_temp_view_93bcf0`: Pivot the fruit table by country and sum the amount for each fruit and country combination. Thought: Spark SQL does not support dynamic pivot operations, which are required to transpose the table as requested. I should get all the distinct values of column country. Action: query_sql_db -Action Input: "SELECT DISTINCT Country FROM spark_ai_temp_view_93bcf0" +Action Input: "SELECT DISTINCT `Country` FROM spark_ai_temp_view_93bcf0" Observation: USA, Canada, Mexico, China Thought: I can write a query to pivot the table by country and sum the amount for each fruit and country combination. Action: query_validation -Action Input: SELECT * FROM spark_ai_temp_view_93bcf0 PIVOT (SUM(Amount) FOR Country IN ('USA', 'Canada', 'Mexico', 'China')) +Action Input: SELECT * FROM spark_ai_temp_view_93bcf0 PIVOT (SUM(Amount) FOR `Country` IN ('USA', 'Canada', 'Mexico', 'China')) Observation: OK Thought:I now know the final answer. -Final Answer: SELECT * FROM spark_ai_temp_view_93bcf0 PIVOT (SUM(Amount) FOR Country IN ('USA', 'Canada', 'Mexico', 'China'))""" +Final Answer: SELECT * FROM spark_ai_temp_view_93bcf0 PIVOT (SUM(Amount) FOR `Country` IN ('USA', 'Canada', 'Mexico', 'China'))""" """QUESTION: Given a Spark temp view `spark_ai_temp_view_19acs2` with the following columns: ``` -Car STRING +Car Name STRING Color STRING Make STRING ``` -Write a Spark SQL query to retrieve from view `spark_ai_temp_view_19acs2`: If color is gold, what is the total number of cars? -Thought: I will use the column 'Color' to filter the rows where its value is 'gold' and then select the COUNT(`Car`) -because COUNT gives me the total number of cars. +Write a Spark SQL query to retrieve from view `spark_ai_temp_view_19acs2`: What is the total number of cars that are gold? +Thought: I should filter on the `Color` column to find the gold cars. +I will now use the tool similar_value to help me choose my filter value. +Action: similar_value +Action Input: gold|Color|spark_ai_temp_view_19acs2 +Observation: gold +Thought: The correct Color filter should be 'gold' because it is semantically closest to the keyword. I will use this in my query. +I will use the column 'Color' to filter the rows where its value is 'gold' and then select the COUNT(`Car Name`) because COUNT gives me the total number of cars. Action: query_validation -Action Input: SELECT COUNT(`Car`) FROM spark_ai_temp_view_19acs2 WHERE `Color` = 'gold' +Action Input: SELECT COUNT(`Car Name`) FROM spark_ai_temp_view_19acs2 WHERE `Color` = 'gold' Observation: OK Thought: I now know the final answer. -Final Answer: SELECT COUNT(`Car`) FROM spark_ai_temp_view_19acs2 WHERE `Color` = 'gold'""" +Final Answer: SELECT COUNT(`Car Name`) FROM spark_ai_temp_view_19acs2 WHERE `Color` = 'gold'""" + """QUESTION: Given a Spark temp view `spark_ai_temp_view_19acs2` with the following columns: +``` +Student STRING +Birthday STRING +``` +Write a Spark SQL query to retrieve from view `spark_ai_temp_view_12qcl3`: Who is the student with the birthday January 1, 2006?
Let's make this question "What is the total number of students with the birthday January 1, 2006?" and remove the example above. The fewer examples, the lower the cost it is. These two seems able to be combined.
pyspark-ai
github_2023
python
119
pyspark-ai
gengliangwang
@@ -119,7 +149,8 @@ SPARK_SQL_PREFIX = """You are an assistant for writing professional Spark SQL queries. Given a question, you need to write a Spark SQL query to answer the question. The result is ALWAYS a Spark SQL query. -""" +ALWAYS use the tool similar_value to find the correct filter value format.
Shall we make it optional? Only when the assistant is not sure about the column value
pyspark-ai
github_2023
python
119
pyspark-ai
gengliangwang
@@ -51,28 +64,32 @@ Write a Spark SQL query to retrieve from view `spark_ai_temp_view_93bcf0`: Pivot the fruit table by country and sum the amount for each fruit and country combination. Thought: Spark SQL does not support dynamic pivot operations, which are required to transpose the table as requested. I should get all the distinct values of column country. Action: query_sql_db -Action Input: "SELECT DISTINCT Country FROM spark_ai_temp_view_93bcf0" +Action Input: "SELECT DISTINCT `Country` FROM spark_ai_temp_view_93bcf0" Observation: USA, Canada, Mexico, China Thought: I can write a query to pivot the table by country and sum the amount for each fruit and country combination. Action: query_validation -Action Input: SELECT * FROM spark_ai_temp_view_93bcf0 PIVOT (SUM(Amount) FOR Country IN ('USA', 'Canada', 'Mexico', 'China')) +Action Input: SELECT * FROM spark_ai_temp_view_93bcf0 PIVOT (SUM(Amount) FOR `Country` IN ('USA', 'Canada', 'Mexico', 'China')) Observation: OK Thought:I now know the final answer. -Final Answer: SELECT * FROM spark_ai_temp_view_93bcf0 PIVOT (SUM(Amount) FOR Country IN ('USA', 'Canada', 'Mexico', 'China'))""" - """QUESTION: Given a Spark temp view `spark_ai_temp_view_19acs2` with the following columns: +Final Answer: SELECT * FROM spark_ai_temp_view_93bcf0 PIVOT (SUM(Amount) FOR `Country` IN ('USA', 'Canada', 'Mexico', 'China'))""" + """QUESTION: Given a Spark temp view `spark_ai_temp_view_12qcl3` with the following columns: ``` -Car STRING -Color STRING -Make STRING +Student STRING +Birthday STRING ``` -Write a Spark SQL query to retrieve from view `spark_ai_temp_view_19acs2`: If color is gold, what is the total number of cars? -Thought: I will use the column 'Color' to filter the rows where its value is 'gold' and then select the COUNT(`Car`) -because COUNT gives me the total number of cars. +Write a Spark SQL query to retrieve from view `spark_ai_temp_view_12qcl3`: What is the total number of students with the birthday January 1, 2006? +Thought: I need to filter by an exact birthday value from the df. I will use the tool similar_value to help me choose my filter value. +Action: similar_value +Action Input: January 1, 2006|Birthday|spark_ai_temp_view_12qcl3
In the followup PR for tests, we should test the similar scores of January 1, 2006 with some dates
pyspark-ai
github_2023
python
116
pyspark-ai
gengliangwang
@@ -102,11 +103,16 @@ def get_tables_and_questions(source_file): sqls.append(item['sql']) return tables, questions, results, sqls +def similarity(spark_ai_result, expected_result):
We should use the similarity in the transform_df method and ask gpt to pick to most relevant column value.
pyspark-ai
github_2023
python
116
pyspark-ai
gengliangwang
@@ -59,6 +59,20 @@ Observation: OK Thought:I now know the final answer. Final Answer: SELECT * FROM spark_ai_temp_view_93bcf0 PIVOT (SUM(Amount) FOR Country IN ('USA', 'Canada', 'Mexico', 'China'))""" + """QUESTION: Given a Spark temp view `spark_ai_temp_view_19acs2` with the following columns: +``` +Car STRING +Color STRING +Make STRING +``` +Write a Spark SQL query to retrieve from view `spark_ai_temp_view_19acs2`: If color is gold, what is the total number of cars? +Thought: I will use the column 'Color' to filter the rows where its value is 'gold' and then select the COUNT(`Car`) +because COUNT gives me the total number of cars. I do not use SUM because SUM is not for counting total number.
can there be a case where we need to use sum for total number?
pyspark-ai
github_2023
python
116
pyspark-ai
gengliangwang
@@ -84,15 +98,29 @@ ] SPARK_SQL_SUFFIX = """\nQuestion: Given a Spark temp view `{view_name}` {comment}. -It contains the following columns: +The dataframe contains the column names and types in this format: +column_name: type. +It's very important to ONLY use the verbatim column names in your resulting SQL query. +For example, the verbatim column name from the line 'Fruit Color: string' is 'Fruit Color'. +So, a resulting SQL query would be: SELECT * FROM view WHERE 'Fruit Color' = 'orange'.
shall we use backtick instead of single quote? Single quote means string literal in Spark SQL
pyspark-ai
github_2023
python
116
pyspark-ai
gengliangwang
@@ -102,11 +103,16 @@ def get_tables_and_questions(source_file): sqls.append(item['sql']) return tables, questions, results, sqls +def similarity(spark_ai_result, expected_result): + import spacy + + spacy_model = spacy.load('en_core_web_lg') + return spacy_model(spark_ai_result).similarity(spacy_model(expected_result)) if __name__ == '__main__': parser = ArgumentParser() - parser.add_argument('--table_file', help='table definition file', default='data/test_sample.tables.jsonl') - parser.add_argument('--source_file', help='source file for the prediction', default='data/test_sample.jsonl') + parser.add_argument('--table_file', help='table definition file', default='data/test_sample1.tables1.jsonl')
let revert these two lines too
pyspark-ai
github_2023
python
104
pyspark-ai
xinrong-meng
@@ -0,0 +1,130 @@ +import json +import re +from argparse import ArgumentParser + +from babel.numbers import parse_decimal, NumberFormatError +from pyspark.sql import SparkSession + +from pyspark_ai import SparkAI + + +def generate_sql_statements(table_file): + sql_statements = [] + num_re = re.compile(r'[-+]?\d*\.\d+|\d+') + with open(table_file, 'r') as f: + for line in f: + item = json.loads(line.strip()) + + table_name = item['id'] + # quote the headers with backticks + headers = ["`{}`".format(h) for h in item['header']] + header_str = "(" + ",".join(headers) + ")" + rows = item['rows'] + + values_str_list = [] + + for row in rows: + vals = [] + for val in row: + if isinstance(val, str): + val = "'{}'".format(val.lower().replace("'", "''").replace("\\", "\\\\")) + else: + val = str(float(val)) + vals.append(val) + + # Convert each value in the row to a string and escape single quotes + values_str_list.append("(" + ",".join(vals) + ")") + + values_str = ",".join(values_str_list) + create_statement = f"CREATE TEMP VIEW `{table_name}` AS SELECT * FROM VALUES {values_str} as {header_str};" + sql_statements.append(create_statement) + + return sql_statements + + +# Reconstruction of the original query from the table id and standard query format +def get_sql_query(table_id, select_index, aggregation_index, conditions): + agg_ops = ['', 'MAX', 'MIN', 'COUNT', 'SUM', 'AVG'] + cond_ops = ['=', '>', '<', 'OP'] + num_re = re.compile(r'[-+]?\d*\.\d+|\d+') + df = spark.table(f"`{table_id}`") + select = df.columns[select_index] + agg = agg_ops[aggregation_index] + if agg != 0: + select = f"{agg}({select})" + where_clause = [] + for col_index, op, val in conditions: + if isinstance(val, str): + val = f"'{val.lower()}'" + if df.dtypes[col_index][1] == 'double' and not isinstance(val, (int, float)): + try: + val = float(parse_decimal(val)) + except NumberFormatError as e: + val = float(num_re.findall(val)[0]) + where_clause.append(f"`{df.columns[col_index]}` {cond_ops[op]} {val}") + where_str = '' + if where_clause: + where_str = 'WHERE ' + ' AND '.join(where_clause) + return f"SELECT `{select}` FROM `{table_id}` {where_str}" + + +# Parse questions and tables from the source file +def get_tables_and_questions(source_file): + tables = [] + questions = [] + results = [] + sqls = [] + with open(source_file, 'r') as f: + for line in f: + item = json.loads(line.strip()) + tables.append(item['table_id']) + questions.append(item['question']) + results.append(item['result']) + sqls.append(item['sql']) + return tables, questions, results, sqls + + +if __name__ == '__main__': + parser = ArgumentParser() + parser.add_argument('--table_file', help='table definition file', default='data/test_sample.tables.jsonl') + parser.add_argument('--source_file', help='source file for the prediction', default='data/test_sample.jsonl') + args = parser.parse_args() + + table_file = args.table_file + statements = generate_sql_statements(table_file) + spark = SparkSession.builder.getOrCreate() + for stmt in statements: + spark.sql(stmt) + + source_file = args.source_file + tables, questions, results, sqls = get_tables_and_questions(source_file) + spark_ai = SparkAI(spark_session=spark, verbose=False) + matched = 0 + # Create sql query for each question and table + for table, question, expected_result, sql in zip(tables, questions, results, sqls): + df = spark.table(f"`{table}`") + try: + query = spark_ai._get_transform_sql_query(df=df, desc=question, cache=True).lower() + result_df = spark.sql(query) + except Exception as e: + print(e) + continue + spark_ai.commit() + found_match = False + spark_ai_result = [] + for i in range(len(result_df.columns)): + spark_ai_result = result_df.rdd.map(lambda row: row[i]).collect() + if spark_ai_result == expected_result: + matched += 1 + found_match = True + break + if not found_match: + print("Question: {}".format(question)) + print("Expected query: {}".format(get_sql_query(table, sql["sel"], sql["agg"], sql["conds"]))) + print("Actual query: {}".format(query)) + print("Expected result: {}".format(expected_result)) + print("Actual result: {}".format(spark_ai_result)) + print("") + + print(f"Matched {matched} out of {len(results)}")
nit: Shall we add the accuracy percentage for easier comparison? Fine to do it as a follow-up though.
pyspark-ai
github_2023
python
104
pyspark-ai
xinrong-meng
@@ -0,0 +1,130 @@ +import json +import re +from argparse import ArgumentParser + +from babel.numbers import parse_decimal, NumberFormatError +from pyspark.sql import SparkSession + +from pyspark_ai import SparkAI + + +def generate_sql_statements(table_file):
nit: Shall we add a docstring to call out the sqls generated are to represent tables as views?
pyspark-ai
github_2023
python
104
pyspark-ai
xinrong-meng
@@ -327,14 +333,42 @@ def create_df( return self._create_dataframe_with_llm(page_content, desc, columns, cache) def _get_transform_sql_query_from_agent( - self, temp_view_name: str, schema: str, desc: str + self, temp_view_name: str, schema: str, sample_rows_str: str, desc: str ) -> str: llm_result = self._sql_agent.run( - view_name=temp_view_name, columns=schema, desc=desc + view_name=temp_view_name, + columns=schema, + sample_rows=sample_rows_str, + desc=desc, ) sql_query_from_response = AIUtils.extract_code_blocks(llm_result)[0] return sql_query_from_response + def _convert_row_as_tuple(self, row: Row) -> tuple: + return tuple(map(str, row.asDict().values())) + + def _get_dataframe_results(self, df: DataFrame) -> list: + return list(map(self._convert_row_as_tuple, df.collect())) + + def _get_sample_spark_rows(self, df: DataFrame, temp_view_name: str) -> str: + if self._sample_rows_in_table_info <= 0: + return "" + columns_str = "\t".join(list(map(lambda f: f.name, df.schema.fields))) + try: + sample_rows = self._get_dataframe_results(df.limit(3)) + # save the sample rows in string format + sample_rows_str = "\n".join(["\t".join(row) for row in sample_rows]) + except Exception:
Do we want sampling to fail silently?
pyspark-ai
github_2023
python
104
pyspark-ai
xinrong-meng
@@ -327,14 +333,42 @@ def create_df( return self._create_dataframe_with_llm(page_content, desc, columns, cache) def _get_transform_sql_query_from_agent( - self, temp_view_name: str, schema: str, desc: str + self, temp_view_name: str, schema: str, sample_rows_str: str, desc: str ) -> str: llm_result = self._sql_agent.run( - view_name=temp_view_name, columns=schema, desc=desc + view_name=temp_view_name, + columns=schema, + sample_rows=sample_rows_str, + desc=desc, ) sql_query_from_response = AIUtils.extract_code_blocks(llm_result)[0] return sql_query_from_response + def _convert_row_as_tuple(self, row: Row) -> tuple: + return tuple(map(str, row.asDict().values())) + + def _get_dataframe_results(self, df: DataFrame) -> list: + return list(map(self._convert_row_as_tuple, df.collect())) + + def _get_sample_spark_rows(self, df: DataFrame, temp_view_name: str) -> str: + if self._sample_rows_in_table_info <= 0: + return "" + columns_str = "\t".join(list(map(lambda f: f.name, df.schema.fields)))
nit: `columns_str = "\t".join([f.name for f in df.schema.fields])`
pyspark-ai
github_2023
python
91
pyspark-ai
gengliangwang
@@ -5,7 +5,13 @@ from typing import Callable, List, Optional from urllib.parse import urlparse -import pandas as pd # noqa: F401 +# We only try to import pandas here to circumvent certain issues +# when the generated code assumes that pandas needs to be imported +# before actually evaluating the code. +try:
Shall we move this block under method `plot_df`?
pyspark-ai
github_2023
python
94
pyspark-ai
gengliangwang
@@ -205,5 +205,81 @@ def test_analysis_handling(self): self.assertEqual(left, right) +class SparkConnectTestCase(unittest.TestCase): + + @classmethod + def setUpClass(cls): + cls.spark = SparkSession.builder.remote("sc://localhost").getOrCreate() + + @classmethod + def tearDownClass(cls): + cls.spark.stop() + +class SparkConnectTests(SparkConnectTestCase): + def setUp(self): + self.spark_ai = SparkAI( + cache_file_location="examples/spark_ai_cache.json", + verbose=True + ) + self.spark_ai.activate() + + def test_spark_connect_autodf_e2e(self):
let's skip the tests in Github Action: ``` @unittest.skip(...) ``` I will enable them later.
pyspark-ai
github_2023
others
94
pyspark-ai
gengliangwang
@@ -35,6 +35,8 @@ google-api-python-client = "^2.90.0" chispa = "^0.9.2" grpcio = ">=1.48.1" plotly = "^5.15.0" +pyarrow = "^12.0.1"
Let's make it consistent with Spark: https://github.com/apache/spark/blob/master/python/setup.py#L134 pyarrow = ">=4.0.0"
pyspark-ai
github_2023
others
94
pyspark-ai
gengliangwang
@@ -35,6 +35,8 @@ google-api-python-client = "^2.90.0" chispa = "^0.9.2" grpcio = ">=1.48.1" plotly = "^5.15.0" +pyarrow = "^12.0.1" +grpcio-status = ">=1.48,<1.57"
">=1.56.0"
pyspark-ai
github_2023
others
82
pyspark-ai
gengliangwang
@@ -33,6 +33,8 @@ pygments = "^2.15.1" google-api-python-client = "^2.90.0" chispa = "^0.9.2" grpcio = ">=1.48.1" +plotly = "^5.15.0" +pyspark = "^3.4.0"
@vjr pyspark is listed as dev dependency below
pyspark-ai
github_2023
others
90
pyspark-ai
gengliangwang
@@ -27,7 +27,7 @@ requests = "^2.31.0" tiktoken = "0.4.0" beautifulsoup4 = "^4.12.2" openai = "^0.27.8" -langchain = "^0.0.201" +langchain >= 0.0.220, < 0.1.0
```suggestion langchain = ">=0.0.201,<0.1.0" ```
pyspark-ai
github_2023
python
81
pyspark-ai
gengliangwang
@@ -153,6 +153,7 @@ 1. function definition f, in Python (Do NOT surround the function definition with quotes) 2. 1 blank new line 3. Call f on df and assign the result to a variable, result: result = name_of_f(df) +Do not include any explanation in English. For example, do NOT include "Here is your output:"
Shall we try `The answer MUST contain python code only`
pyspark-ai
github_2023
python
77
pyspark-ai
gengliangwang
@@ -391,6 +391,13 @@ def verify_df(self, df: DataFrame, desc: str, cache: bool = True) -> None: """ tags = self._get_tags(cache) llm_output = self._verify_chain.run(tags=tags, df=df, desc=desc) + + if "```" in llm_output:
let's use the `_extract_code_blocks` method here.
pyspark-ai
github_2023
python
77
pyspark-ai
allisonwang-db
@@ -150,13 +150,12 @@ 2. 1 blank new line 3. Call f on df and assign the result to a variable, result: result = name_of_f(df) -Include any necessary import statements INSIDE the function definition. -For example: +Include any necessary import statements INSIDE the function definition, like this: def gen_random(): import random return random.randint(0, 10) -For example: +Your output must follow the format of the example below, exactly:
Do we have a test for this to prevent regressions?
pyspark-ai
github_2023
others
20
pyspark-ai
gengliangwang
@@ -80,70 +80,70 @@ "\n", "\u001b[92mINFO: \u001b[0mSQL query for the ingestion:\n", "\u001b[34mCREATE\u001b[39;49;00m\u001b[37m \u001b[39;49;00m\u001b[34mOR\u001b[39;49;00m\u001b[37m \u001b[39;49;00m\u001b[34mREPLACE\u001b[39;49;00m\u001b[37m \u001b[39;49;00mTEMP\u001b[37m \u001b[39;49;00m\u001b[34mVIEW\u001b[39;49;00m\u001b[37m \u001b[39;49;00mauto_sales_2022\u001b[37m \u001b[39;49;00m\u001b[34mAS\u001b[39;49;00m\u001b[37m \u001b[39;49;00m\u001b[34mSELECT\u001b[39;49;00m\u001b[37m \u001b[39;49;00m*\u001b[37m \u001b[39;49;00m\u001b[34mFROM\u001b[39;49;00m\u001b[37m \u001b[39;49;00m\u001b[34mVALUES\u001b[39;49;00m\u001b[37m\u001b[39;49;00m\n", - "(\u001b[33m'Toyota'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m1849751\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m-\u001b[34m9\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", - "(\u001b[33m'Ford'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m1767439\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m-\u001b[34m2\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", - "(\u001b[33m'Chevrolet'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m1502389\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m6\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", - "(\u001b[33m'Honda'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m881201\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m-\u001b[34m33\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", - "(\u001b[33m'Hyundai'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m724265\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m-\u001b[34m2\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", - "(\u001b[33m'Kia'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m693549\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m-\u001b[34m1\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", - "(\u001b[33m'Jeep'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m684612\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m-\u001b[34m12\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", - "(\u001b[33m'Nissan'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m682731\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m-\u001b[34m25\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", - "(\u001b[33m'Subaru'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m556581\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m-\u001b[34m5\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", - "(\u001b[33m'Ram Trucks'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m545194\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m-\u001b[34m16\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", - "(\u001b[33m'GMC'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m517649\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m7\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", - "(\u001b[33m'Mercedes-Benz'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m350949\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m7\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", - "(\u001b[33m'BMW'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m332388\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m-\u001b[34m1\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", - "(\u001b[33m'Volkswagen'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m301069\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m-\u001b[34m20\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", - "(\u001b[33m'Mazda'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m294908\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m-\u001b[34m11\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", - "(\u001b[33m'Lexus'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m258704\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m-\u001b[34m15\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", - "(\u001b[33m'Dodge'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m190793\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m-\u001b[34m12\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", - "(\u001b[33m'Audi'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m186875\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m-\u001b[34m5\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", - "(\u001b[33m'Cadillac'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m134726\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m14\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", - "(\u001b[33m'Chrysler'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m112713\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m-\u001b[34m2\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", - "(\u001b[33m'Buick'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m103519\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m-\u001b[34m42\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", - "(\u001b[33m'Acura'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m102306\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m-\u001b[34m35\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", - "(\u001b[33m'Volvo'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m102038\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m-\u001b[34m16\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", - "(\u001b[33m'Mitsubishi'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m102037\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m-\u001b[34m16\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", - "(\u001b[33m'Lincoln'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m83486\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m-\u001b[34m4\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", - "(\u001b[33m'Porsche'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m70065\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m0\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", - "(\u001b[33m'Genesis'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m56410\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m14\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", - "(\u001b[33m'INFINITI'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m46619\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m-\u001b[34m20\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", - "(\u001b[33m'MINI'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m29504\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m-\u001b[34m1\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", - "(\u001b[33m'Alfa Romeo'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m12845\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m-\u001b[34m30\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", - "(\u001b[33m'Maserati'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m6413\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m-\u001b[34m10\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", - "(\u001b[33m'Bentley'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m3975\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m0\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", - "(\u001b[33m'Lamborghini'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m3134\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m3\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", - "(\u001b[33m'Fiat'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m915\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m-\u001b[34m61\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", - "(\u001b[33m'McLaren'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m840\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m-\u001b[34m35\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", - "(\u001b[33m'Rolls-Royce'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m460\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m7\u001b[39;49;00m)\u001b[37m\u001b[39;49;00m\n", - "\u001b[34mAS\u001b[39;49;00m\u001b[37m \u001b[39;49;00mv1(brand,\u001b[37m \u001b[39;49;00mus_sales,\u001b[37m \u001b[39;49;00msales_change)\u001b[37m\u001b[39;49;00m\n", + "(\u001b[33m'Toyota'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m1849751\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[33m'Down'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m9\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", + "(\u001b[33m'Ford'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m1767439\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[33m'Down'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m2\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", + "(\u001b[33m'Chevrolet'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m1502389\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[33m'Up'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m6\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", + "(\u001b[33m'Honda'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m881201\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[33m'Down'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m33\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", + "(\u001b[33m'Hyundai'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m724265\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[33m'Down'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m2\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", + "(\u001b[33m'Kia'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m693549\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[33m'Down'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m1\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", + "(\u001b[33m'Jeep'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m684612\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[33m'Down'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m12\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", + "(\u001b[33m'Nissan'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m682731\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[33m'Down'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m25\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", + "(\u001b[33m'Subaru'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m556581\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[33m'Down'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m5\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", + "(\u001b[33m'Ram Trucks'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m545194\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[33m'Down'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m16\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", + "(\u001b[33m'GMC'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m517649\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[33m'Up'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m7\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", + "(\u001b[33m'Mercedes-Benz'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m350949\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[33m'Up'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m7\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", + "(\u001b[33m'BMW'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m332388\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[33m'Down'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m1\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", + "(\u001b[33m'Volkswagen'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m301069\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[33m'Down'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m20\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", + "(\u001b[33m'Mazda'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m294908\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[33m'Down'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m11\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", + "(\u001b[33m'Lexus'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m258704\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[33m'Down'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m15\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", + "(\u001b[33m'Dodge'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m190793\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[33m'Down'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m12\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", + "(\u001b[33m'Audi'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m186875\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[33m'Down'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m5\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", + "(\u001b[33m'Cadillac'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m134726\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[33m'Up'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m14\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", + "(\u001b[33m'Chrysler'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m112713\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[33m'Down'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m2\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", + "(\u001b[33m'Buick'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m103519\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[33m'Down'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m42\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", + "(\u001b[33m'Acura'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m102306\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[33m'Down'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m35\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", + "(\u001b[33m'Volvo'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m102038\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[33m'Down'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m16\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", + "(\u001b[33m'Mitsubishi'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m102037\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[33m'Down'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m16\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", + "(\u001b[33m'Lincoln'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m83486\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[33m'Down'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m4\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", + "(\u001b[33m'Porsche'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m70065\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[33m'Flat'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m0\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", + "(\u001b[33m'Genesis'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m56410\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[33m'Up'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m14\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", + "(\u001b[33m'INFINITI'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m46619\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[33m'Down'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m20\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", + "(\u001b[33m'MINI'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m29504\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[33m'Down'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m1\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", + "(\u001b[33m'Alfa Romeo'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m12845\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[33m'Down'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m30\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", + "(\u001b[33m'Maserati'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m6413\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[33m'Down'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m10\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", + "(\u001b[33m'Bentley'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m3975\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[33m'Flat'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m0\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", + "(\u001b[33m'Lamborghini'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m3134\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[33m'Up'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m3\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", + "(\u001b[33m'Fiat'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m915\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[33m'Down'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m61\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", + "(\u001b[33m'McLaren'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m840\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[33m'Down'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m35\u001b[39;49;00m),\u001b[37m\u001b[39;49;00m\n", + "(\u001b[33m'Rolls-Royce'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m460\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[33m'Up'\u001b[39;49;00m,\u001b[37m \u001b[39;49;00m\u001b[34m7\u001b[39;49;00m)\u001b[37m\u001b[39;49;00m\n", + "\u001b[34mAS\u001b[39;49;00m\u001b[37m \u001b[39;49;00mv1(brand,\u001b[37m \u001b[39;49;00mus_sales,\u001b[37m \u001b[39;49;00mchange_direction,\u001b[37m \u001b[39;49;00mchange_percentage)\u001b[37m\u001b[39;49;00m\n", "\n", "\u001b[92mINFO: \u001b[0mStoring data into temp view: auto_sales_2022\n", "\n", - "+-------------+--------+------------+\n", - "| brand|us_sales|sales_change|\n", - "+-------------+--------+------------+\n", - "| Toyota| 1849751| -9|\n", - "| Ford| 1767439| -2|\n", - "| Chevrolet| 1502389| 6|\n", - "| Honda| 881201| -33|\n", - "| Hyundai| 724265| -2|\n", - "| Kia| 693549| -1|\n", - "| Jeep| 684612| -12|\n", - "| Nissan| 682731| -25|\n", - "| Subaru| 556581| -5|\n", - "| Ram Trucks| 545194| -16|\n", - "| GMC| 517649| 7|\n", - "|Mercedes-Benz| 350949| 7|\n", - "| BMW| 332388| -1|\n", - "| Volkswagen| 301069| -20|\n", - "| Mazda| 294908| -11|\n", - "| Lexus| 258704| -15|\n", - "| Dodge| 190793| -12|\n", - "| Audi| 186875| -5|\n", - "| Cadillac| 134726| 14|\n", - "| Chrysler| 112713| -2|\n", - "+-------------+--------+------------+\n", + "+-------------+--------+----------------+-----------------+\n", + "| brand|us_sales|change_direction|change_percentage|\n", + "+-------------+--------+----------------+-----------------+\n", + "| Toyota| 1849751| Down| 9|\n",
Shall we rerun this one. It doesn't look good to have `change_direction`
pyspark-ai
github_2023
python
2
pyspark-ai
gengliangwang
@@ -131,3 +131,19 @@ PLOT_PROMPT = PromptTemplate( input_variables=["columns", "explain"], template=PLOT_PROMPT_TEMPLATE ) + +TEST_TEMPLATE = """ +You are an Apache Spark SQL expert, with experience writing robust test cases for PySpark code. +Given a PySpark function which transforms a dataframe, write a unit test class in Python with +methods to test the given PySpark function. + +The answer must contain ONLY the code for the unit test class with the test cases (no explanation words). +Do NOT include a main class footer (e.g. do NOT include "if __name__ == '__main__':") +Please do include all necessary imports. + +Here is the function: {function}
So the test is totally based on function name? Seems hacky. Shall we make this code generation as a notebook magic instead of an API?
pyspark-ai
github_2023
others
3
pyspark-ai
gengliangwang
@@ -15,19 +15,19 @@ classifiers = [ "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8",
why dropping python 3.8? We should support it.
pyspark-ai
github_2023
python
5
pyspark-ai
allisonwang-db
@@ -234,6 +237,26 @@ def plot_df(self, df: DataFrame) -> None: code = response.content.replace("```python", "```").split("```")[1] exec(code) +# def udf_llm(self, header: str, desc: str): +# code = self._udf_chain.run( +# desc=desc +# ) +# # reformat, add indent for each line +# code_split = code.split("\n") +# new_code = "\n\t".join(code_split) + +# udf = f"""def {header}:\n\t{new_code}""" +# self.log(f"UDF:\n{udf}") + + def udf_llm(self, desc: str):
How about let's make it a decorator. Similar to the current `@udf` API in PySpark. For example ``` @assistant.udf(returnType="int") def my_udf(x: int): """Description of the udf" ... ```
pyspark-ai
github_2023
python
5
pyspark-ai
gengliangwang
@@ -166,3 +166,50 @@ """ VERIFY_PROMPT = PromptTemplate(input_variables=["df", "desc"], template=VERIFY_TEMPLATE) + +UDF_TEMPLATE = """ +This is the documentation for a PySpark user-defined function (udf): pyspark.sql.functions.udf + +A udf creates a deterministic, reusable function in Spark. It can take any data type as a parameter, +and by default returns a String (although it can return any data type). +The point is to reuse a function on several dataframes and SQL functions. + +Given 1) input arguments, 2) a description of the udf functionality, and 3) the udf return type, +generate and return a callable udf. + +Here is example 1:
Let's use the few_shot_examples from langchain to build the prompt https://python.langchain.com/docs/modules/model_io/prompts/prompt_templates/few_shot_examples
pyspark-ai
github_2023
python
1
pyspark-ai
allisonwang-db
@@ -119,3 +119,64 @@ Assume the result of the Spark SQL query is stored in a dataframe named 'df', visualize the query result using plotly. There is no need to install any package with pip. """ + +VERIFY_TEMPLATE = """ +Given 1) a PySpark dataframe, my_df, and 2) a description of expected properties, desc, +generate a Python function to test whether the given dataframe satisfies the expected properties. +Your generated function should take 1 parameter, df, and the return type should be a boolean. +You will call the function, passing in my_df as the parameter, and return the output (True/False).
shall we ask the llm to generate the code that contains the function, and we can execute the generated code to get the result (True/False). I don't think the llm can directly execute the code generated.
pyspark-ai
github_2023
python
1
pyspark-ai
allisonwang-db
@@ -119,3 +119,64 @@ Assume the result of the Spark SQL query is stored in a dataframe named 'df', visualize the query result using plotly. There is no need to install any package with pip. """ + +VERIFY_TEMPLATE = """ +Given 1) a PySpark dataframe, my_df, and 2) a description of expected properties, desc, +generate a Python function to test whether the given dataframe satisfies the expected properties. +Your generated function should take 1 parameter, df, and the return type should be a boolean. +You will call the function, passing in my_df as the parameter, and return the output (True/False). + +In total, your output must contain ONLY the following code (no explanation words): +1. Function definition, in Python +2. Run the function with given dataframe, my_df, passed in as parameter +3. Boolean indicating whether my_df satisfies the expectation described in desc (True/False) +Your output MUST contain EACH of the above three things. + +For example: +Input: +my_df = spark.createDataFrame(data=[("Alice", 25), ("Bob", 30), ("Charlie", 35)], schema=["Name", "Age"]) +desc = "expect 5 columns" + +Output: +"def has_5_columns(df) -> bool: + # Get the number of columns in the DataFrame + num_columns = len(df.columns) + + # Check if the number of columns is equal to 5 + if num_columns == 5: + return True + else: + return False +has_5_columns(df=my_df) -> Result: False"
For example, here we can ask LLM to generate this line ```suggestion has_5_columns(df=my_df) ``` and we can execute the code to get the actual result
pyspark-ai
github_2023
python
1
pyspark-ai
allisonwang-db
@@ -119,3 +119,64 @@ Assume the result of the Spark SQL query is stored in a dataframe named 'df', visualize the query result using plotly. There is no need to install any package with pip. """ + +VERIFY_TEMPLATE = """ +Given 1) a PySpark dataframe, my_df, and 2) a description of expected properties, desc, +generate a Python function to test whether the given dataframe satisfies the expected properties. +Your generated function should take 1 parameter, df, and the return type should be a boolean. +You will call the function, passing in my_df as the parameter, and return the output (True/False). + +In total, your output must contain ONLY the following code (no explanation words): +1. Function definition, in Python +2. Run the function with given dataframe, my_df, passed in as parameter +3. Boolean indicating whether my_df satisfies the expectation described in desc (True/False) +Your output MUST contain EACH of the above three things. + +For example: +Input: +my_df = spark.createDataFrame(data=[("Alice", 25), ("Bob", 30), ("Charlie", 35)], schema=["Name", "Age"]) +desc = "expect 5 columns" + +Output: +"def has_5_columns(df) -> bool: + # Get the number of columns in the DataFrame + num_columns = len(df.columns) + + # Check if the number of columns is equal to 5 + if num_columns == 5: + return True + else: + return False +has_5_columns(df=my_df) -> Result: False" + +Output Template: +"def verify_func(df) -> bool: + ... +verify_func(df=my_df) -> Result: result" + +Here is your input df: {my_df} +Here is your input description: {desc} +""" + +VERIFY_PROMPT = PromptTemplate( + input_variables=["my_df", "desc"], template=VERIFY_TEMPLATE +) + +TEST_TEMPLATE = """
Maybe we can add this in a separate PR.
pyspark-ai
github_2023
python
1
pyspark-ai
gengliangwang
@@ -119,3 +119,64 @@ Assume the result of the Spark SQL query is stored in a dataframe named 'df', visualize the query result using plotly. There is no need to install any package with pip. """ + +VERIFY_TEMPLATE = """ +Given 1) a PySpark dataframe, my_df, and 2) a description of expected properties, desc,
Shall we use `df` instead of `my_df`? Also, it would be great to quote the variable name
pyspark-ai
github_2023
python
1
pyspark-ai
gengliangwang
@@ -119,3 +119,64 @@ Assume the result of the Spark SQL query is stored in a dataframe named 'df', visualize the query result using plotly. There is no need to install any package with pip. """ + +VERIFY_TEMPLATE = """ +Given 1) a PySpark dataframe, my_df, and 2) a description of expected properties, desc, +generate a Python function to test whether the given dataframe satisfies the expected properties. +Your generated function should take 1 parameter, df, and the return type should be a boolean. +You will call the function, passing in my_df as the parameter, and return the output (True/False). + +In total, your output must contain ONLY the following code (no explanation words): +1. Function definition, in Python +2. Run the function with given dataframe, my_df, passed in as parameter +3. Boolean indicating whether my_df satisfies the expectation described in desc (True/False) +Your output MUST contain EACH of the above three things. + +For example: +Input:
Why do we need to mentiond how df is created?
pyspark-ai
github_2023
python
1
pyspark-ai
gengliangwang
@@ -234,11 +239,41 @@ def plot_df(self, df: DataFrame) -> None: code = response.content.replace("```python", "```").split("```")[1] exec(code) + def verify_df(self, my_df: DataFrame, desc: str) -> None: + """ + This method creates and runs test cases for the provided PySpark dataframe transformation function. + + :param my_df: The Spark DataFrame to be verified + :param desc: A description of the expectation to be verified + """ + test_code = self._verify_chain.run(
will the code be executed? Or just show in the log?
pyspark-ai
github_2023
python
1
pyspark-ai
gengliangwang
@@ -119,3 +119,59 @@ Assume the result of the Spark SQL query is stored in a dataframe named 'df', visualize the query result using plotly. There is no need to install any package with pip. """ + +VERIFY_TEMPLATE = """ +Given 1) a PySpark dataframe, df, and 2) a description of expected properties, desc, +generate a Python function to test whether the given dataframe satisfies the expected properties. +Your generated function should take 1 parameter, df, and the return type should be a boolean. +You will call the function, passing in df as the parameter, and return the output (True/False). + +In total, your output must follow the format below, exactly (no explanation words): +1. function definition f, in Python +2. 1 blank new line +3. FUNCTION_NAME: name_of_f + +For example: +Input: +df = DataFrame[name: string, age: int] +desc = "expect 5 columns" + +Output: +"def has_5_columns(df) -> bool: + # Get the number of columns in the DataFrame + num_columns = len(df.columns) + + # Check if the number of columns is equal to 5 + if num_columns == 5: + return True + else: + return False + +FUNCTION_NAME: has_5_columns" + +Here is your input df: {df} +Here is your input description: {desc} +""" + +VERIFY_PROMPT = PromptTemplate( + input_variables=["df", "desc"], template=VERIFY_TEMPLATE +) + +TEST_TEMPLATE = """
SHall we move the TEST_TEMPLATE to another PR?
pyspark-ai
github_2023
python
1
pyspark-ai
gengliangwang
@@ -234,11 +237,51 @@ def plot_df(self, df: DataFrame) -> None: code = response.content.replace("```python", "```").split("```")[1] exec(code) + def verify_df(self, my_df: DataFrame, desc: str) -> None:
```suggestion def verify_df(self, df: DataFrame, desc: str) -> None: ```
pyspark-ai
github_2023
python
1
pyspark-ai
gengliangwang
@@ -234,11 +237,51 @@ def plot_df(self, df: DataFrame) -> None: code = response.content.replace("```python", "```").split("```")[1] exec(code) + def verify_df(self, my_df: DataFrame, desc: str) -> None: + """ + This method creates and runs test cases for the provided PySpark dataframe transformation function. + + :param my_df: The Spark DataFrame to be verified + :param desc: A description of the expectation to be verified + """ + llm_output = self._verify_chain.run( + my_df=my_df, + desc=desc + ) + function_def = llm_output.split("FUNCTION_NAME: ")[0].strip() + function_name = llm_output.split("FUNCTION_NAME: ")[1].strip() + + test_code = f"""{function_def}\nprint({function_name}(my_df))""" + self.log(f"Generated code:\n{test_code}") + + import sys
shall we use `exec()` on the generated code directly?
biliscope
github_2023
javascript
258
gaogaotiantian
gaogaotiantian
@@ -97,6 +97,15 @@ window.addEventListener("load", function() { ?.querySelector("bili-comment-user-info")?.shadowRoot ?.querySelector("#user-name > a"); userNameA?.addEventListener("mouseover", showProfileDebounce); + + const richText = mainComment.shadowRoot.querySelector("bili-rich-text"); + if (richText) { + tryObserve(richText.shadowRoot);
这里需要做这件事么?text内部是不会再改变的吧?这个observe量还挺大的。
biliscope
github_2023
javascript
258
gaogaotiantian
gaogaotiantian
@@ -97,6 +97,15 @@ window.addEventListener("load", function() { ?.querySelector("bili-comment-user-info")?.shadowRoot ?.querySelector("#user-name > a"); userNameA?.addEventListener("mouseover", showProfileDebounce); + + const richText = mainComment.shadowRoot.querySelector("bili-rich-text"); + if (richText) { + tryObserve(richText.shadowRoot); + const userNameAts = richText.shadowRoot.querySelectorAll("a");
这个query是不是可以稍微再准确一点?因为text里可能还会有比如视频的link或者搜索的link之类的,这里应该可以直接通过attribute定位到user at吧?尽管debounce那里会filter掉,但是如果我们可以在这里比较轻松地做filter感觉是更理想的。
biliscope
github_2023
javascript
258
gaogaotiantian
gaogaotiantian
@@ -109,10 +118,18 @@ window.addEventListener("load", function() { const avatar = userInfo.querySelector("#user-avatar"); avatar?.addEventListener("mouseover", showProfileDebounce); - tryObserve(userInfo.shadowRoot);
我没理解。我觉得这里你的理解是不是出现了一些问题。`tryObserve`的意思是要观察这个`shadowRoot`里面的变化,`userInfo`和`richText`没有任何关系啊,它们是两个tree,它们谁先被render和它们彼此是不是需要被observe是没关系的。 而且在这种PR里非常random地拿掉一个别的地方的代码一般是不太推荐的,除非有很扎实的理由。
biliscope
github_2023
javascript
258
gaogaotiantian
gaogaotiantian
@@ -109,10 +118,18 @@ window.addEventListener("load", function() { const avatar = userInfo.querySelector("#user-avatar"); avatar?.addEventListener("mouseover", showProfileDebounce); - tryObserve(userInfo.shadowRoot); const userNameA = userInfo.shadowRoot?.querySelector("#user-name > a"); userNameA?.addEventListener("mouseover", showProfileDebounce); } + + const richText = reply.shadowRoot.querySelector("bili-rich-text"); + if (richText) { + tryObserve(richText.shadowRoot); + const userNameAts = richText.shadowRoot.querySelectorAll("a[data-user-profile-id]");
想了一下,这里确实需要observe。
biliscope
github_2023
javascript
257
gaogaotiantian
gaogaotiantian
@@ -36,13 +36,19 @@ function labelPopularPage() { function labelDynamicPage() { for (let el of document.getElementsByClassName("bili-dyn-item")) { + if (el.__vue__.author.type == "AUTHOR_TYPE_UGC_SEASON") {
这里正常的user type是固定的么?能不能写成类似 ```javascript const authorType = ... const mid = ... if (authorType == ... && mid) { ... } ``` 的形式。
biliscope
github_2023
javascript
251
gaogaotiantian
gaogaotiantian
@@ -267,6 +273,8 @@ VideoProfileCard.prototype.updateTarget = function(target) { } VideoProfileCard.prototype.drawConclusion = function() { + document.getElementById("biliscope-ai-summary-popup").classList.add("d-none");
这个是为啥?