这是一个简单的示例,构建了一个查询管道,可以对 Pandas 数据框执行结构化操作,以满足用户查询,使用LLMs来推断操作集。
这可以被视为我们的 PandasQueryEngine
的“从头开始”版本。
警告:此工具提供LLM访问eval
函数。
在运行此工具的计算机上可能会发生任意代码执行。
不建议在生产环境中使用此工具,并且需要进行严格的沙盒化或虚拟机化。
%pip install llama-index-llms-openai llama-index-experimental
from llama_index.core.query_pipeline import (
QueryPipeline as QP,
Link,
InputComponent,
)
from llama_index.experimental.query_engine.pandas import (
PandasInstructionParser,
)
from llama_index.llms.openai import OpenAI
from llama_index.core import PromptTemplate
这里我们加载泰坦尼克号的CSV数据集。
!wget 'https://raw.githubusercontent.com/jerryjliu/llama_index/main/docs/docs/examples/data/csv/titanic_train.csv' -O 'titanic_train.csv'
--2024-01-13 18:39:07-- https://raw.githubusercontent.com/jerryjliu/llama_index/main/docs/docs/examples/data/csv/titanic_train.csv Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 2606:50c0:8003::154, 2606:50c0:8001::154, 2606:50c0:8002::154, ... Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|2606:50c0:8003::154|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 57726 (56K) [text/plain] Saving to: ‘titanic_train.csv’ titanic_train.csv 100%[===================>] 56.37K --.-KB/s in 0.007s 2024-01-13 18:39:07 (7.93 MB/s) - ‘titanic_train.csv’ saved [57726/57726]
import pandas as pd
df = pd.read_csv("./titanic_train.csv")
在这里,我们定义了一组模块:
特别是,pandas输出解析器专门设计用于安全执行Python代码。它包括许多安全检查,可能会让人从头开始编写时感到烦人。这包括仅从一组批准的模块中导入(例如,不允许会更改文件系统的模块,如os
),还要确保不调用私有/双下划线方法。
instruction_str = (
"1. Convert the query to executable Python code using Pandas.\n"
"2. The final line of code should be a Python expression that can be called with the `eval()` function.\n"
"3. The code should represent a solution to the query.\n"
"4. PRINT ONLY THE EXPRESSION.\n"
"5. Do not quote the expression.\n"
)
pandas_prompt_str = (
"You are working with a pandas dataframe in Python.\n"
"The name of the dataframe is `df`.\n"
"This is the result of `print(df.head())`:\n"
"{df_str}\n\n"
"Follow these instructions:\n"
"{instruction_str}\n"
"Query: {query_str}\n\n"
"Expression:"
)
response_synthesis_prompt_str = (
"Given an input question, synthesize a response from the query results.\n"
"Query: {query_str}\n\n"
"Pandas Instructions (optional):\n{pandas_instructions}\n\n"
"Pandas Output: {pandas_output}\n\n"
"Response: "
)
pandas_prompt = PromptTemplate(pandas_prompt_str).partial_format(
instruction_str=instruction_str, df_str=df.head(5)
)
pandas_output_parser = PandasInstructionParser(df)
response_synthesis_prompt = PromptTemplate(response_synthesis_prompt_str)
llm = OpenAI(model="gpt-3.5-turbo")
看起来像这样: 输入查询字符串 -> pandas_prompt -> llm1 -> pandas_output_parser -> response_synthesis_prompt -> llm2
与response_synthesis_prompt的额外连接:llm1 -> pandas_instructions,以及pandas_output_parser -> pandas_output。
qp = QP( modules={ "input": InputComponent(), # 输入组件 "pandas_prompt": pandas_prompt, # pandas提示 "llm1": llm, # llm1 "pandas_output_parser": pandas_output_parser, # pandas输出解析器 "response_synthesis_prompt": response_synthesis_prompt, # 响应合成提示 "llm2": llm, # llm2 }, verbose=True, # 详细模式)qp.add_chain(["input", "pandas_prompt", "llm1", "pandas_output_parser"]) # 添加链qp.add_links( # 添加链接 [ Link("input", "response_synthesis_prompt", dest_key="query_str"), # 从输入到响应合成提示的链接 Link( "llm1", "response_synthesis_prompt", dest_key="pandas_instructions" # 从llm1到响应合成提示的链接 ), Link( "pandas_output_parser", "response_synthesis_prompt", dest_key="pandas_output", # 从pandas输出解析器到响应合成提示的链接 ), ])# 添加从响应合成提示到llm2的链接qp.add_link("response_synthesis_prompt", "llm2")
# 运行查询
在这个部分,我们将学习如何运行查询。
response = qp.run(
query_str="What is the correlation between survival and age?",
)
> Running module input with input: query_str: What is the correlation between survival and age? > Running module pandas_prompt with input: query_str: What is the correlation between survival and age? > Running module llm1 with input: messages: You are working with a pandas dataframe in Python. The name of the dataframe is `df`. This is the result of `print(df.head())`: survived pclass name ... > Running module pandas_output_parser with input: input: assistant: df['survived'].corr(df['age']) > Running module response_synthesis_prompt with input: query_str: What is the correlation between survival and age? pandas_instructions: assistant: df['survived'].corr(df['age']) pandas_output: -0.07722109457217755 > Running module llm2 with input: messages: Given an input question, synthesize a response from the query results. Query: What is the correlation between survival and age? Pandas Instructions (optional): df['survived'].corr(df['age']) Pandas ...
print(response.message.content)
The correlation between survival and age is -0.0772. This indicates a weak negative correlation, suggesting that as age increases, the likelihood of survival slightly decreases.