Polars 查询引擎
本指南向您展示如何使用我们的 PolarsQueryEngine:通过大型语言模型将自然语言转换为Polars Python代码。
PolarsQueryEngine 的输入是一个 Polars 数据框,输出是一个响应。LLM 推断需要执行的数据框操作以获取结果。
警告: 此工具为大型语言模型提供了对 eval 函数的访问权限。
在运行此工具的机器上可能发生任意代码执行。
虽然对代码进行了一定程度的过滤,但不建议在生产环境中使用此工具,
除非具备严格沙箱隔离或虚拟机保护措施。
如果您在 Colab 上打开这个笔记本,您可能需要安装 LlamaIndex 🦙。
!pip install llama-index llama-index-experimental polarsimport loggingimport sysfrom IPython.display import Markdown, display
import polars as plfrom llama_index.experimental.query_engine import PolarsQueryEngine
logging.basicConfig(stream=sys.stdout, level=logging.INFO)logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout))让我们从一个玩具数据框开始
Section titled “Let’s start on a Toy DataFrame”这里让我们加载一个包含城市和人口配对的非常简单的数据框,并对其运行 PolarsQueryEngine。
通过设置 verbose=True 我们可以查看中间生成的指令。
# Test on some sample datadf = pl.DataFrame( { "city": ["Toronto", "Tokyo", "Berlin"], "population": [2930000, 13960000, 3645000], })query_engine = PolarsQueryEngine(df=df, verbose=True)response = query_engine.query( "What is the city with the highest population?",)display(Markdown(f"<b>{response}</b>"))# get polars python instructionsprint(response.metadata["polars_instruction_str"])我们还可以采取使用大型语言模型来合成响应的步骤。
query_engine = PolarsQueryEngine(df=df, verbose=True, synthesize_response=True)response = query_engine.query( "What is the city with the highest population? Give both the city and population",)print(str(response))泰坦尼克号数据集是机器学习入门中最受欢迎的表格数据集之一 来源:https://www.kaggle.com/c/titanic
!wget 'https://raw.githubusercontent.com/jerryjliu/llama_index/main/docs/examples/data/csv/titanic_train.csv' -O 'titanic_train.csv'df = pl.read_csv("./titanic_train.csv")query_engine = PolarsQueryEngine(df=df, verbose=True)response = query_engine.query( "What is the correlation between survival and age?",)display(Markdown(f"<b>{response}</b>"))让我们来看看这些提示!
from llama_index.core import PromptTemplatequery_engine = PolarsQueryEngine(df=df, verbose=True)prompts = query_engine.get_prompts()print(prompts["polars_prompt"].template)print(prompts["response_synthesis_prompt"].template)您也可以更新提示词:
new_prompt = PromptTemplate( """\You are working with a polars dataframe in Python.The name of the dataframe is `df`.This is the result of `print(df.head())`:{df_str}
Follow these instructions:{instruction_str}Query: {query_str}
Expression: """)
query_engine.update_prompts({"polars_prompt": new_prompt})这是指令字符串(您可以通过在初始化时传入 instruction_str 来自定义)
instruction_str = """\1. Convert the query to executable Python code using Polars.2. The final line of code should be a Python expression that can be called with the `eval()` function.3. The code should represent a solution to the query.4. PRINT ONLY THE EXPRESSION.5. Do not quote the expression."""如果您想学习使用我们的查询管道语法和上述提示组件构建您自己的Polars查询引擎,可以参考我们的Pandas查询管道教程中的技术方法。