跳到内容

SQL

基于执行的指标

在这些指标中,通过在数据库上执行SQL查询,然后将response与预期结果进行比较,来对比生成的SQL。

DataCompy分数

DataCompyScore指标使用DataCompy,这是一个比较两个pandas DataFrames的Python库。它提供了一个简单的接口来比较两个DataFrame并提供详细的差异报告。在此指标中,将在数据库上执行response,并将生成的数据与预期数据(即reference)进行比较。为了进行比较,responsereference都应采用示例中所示的逗号分隔值(Comma-Separated Values)形式。

可以按行或按列比较DataFrames。这可以使用mode参数进行配置。

如果moderow,则按行进行比较。如果modecolumn,则按列进行比较。

\[ \text{精确率 } = {|\text{响应与参考中匹配的行数}| \over |\text{响应中的总行数}|} \]
\[ \text{精确率 } = {|\text{响应与参考中匹配的行数}| \over |\text{参考中的总行数}|} \]

默认情况下,mode设置为row,指标为F1分数,它是精确率(precision)和召回率(recall)的调和平均数。

from ragas.metrics import DataCompyScore
from ragas.dataset_schema import SingleTurnSample

data1 = """acct_id,dollar_amt,name,float_fld,date_fld
10000001234,123.45,George Maharis,14530.1555,2017-01-01
10000001235,0.45,Michael Bluth,1,2017-01-01
10000001236,1345,George Bluth,,2017-01-01
10000001237,123456,Bob Loblaw,345.12,2017-01-01
10000001238,1.05,Lucille Bluth,,2017-01-01
10000001238,1.05,Loose Seal Bluth,,2017-01-01
"""

data2 = """acct_id,dollar_amt,name,float_fld
10000001234,123.4,George Michael Bluth,14530.155
10000001235,0.45,Michael Bluth,
10000001236,1345,George Bluth,1
10000001237,123456,Robert Loblaw,345.12
10000001238,1.05,Loose Seal Bluth,111
"""
sample = SingleTurnSample(response=data1, reference=data2)
scorer = DataCompyScore()
await scorer.single_turn_ascore(sample)
要将模式更改为按列比较,请将mode参数设置为column

scorer = DataCompyScore(mode="column", metric="recall")

非基于执行的指标

在数据库上执行SQL查询可能很耗时,有时也不可行。在这种情况下,我们可以使用非基于执行的指标来评估SQL查询。这些指标直接比较SQL查询,而无需在数据库上执行它们。

SQL查询语义等价性

LLMSQLEquivalence是一种可用于评估response查询与reference查询等价性的指标。该指标在比较查询时还需要使用数据库模式,这通过reference_contexts输入。该指标是一个二元指标,1表示SQL查询在语义上等价,0表示SQL查询在语义上不等价。

from ragas.metrics import LLMSQLEquivalence
from ragas.dataset_schema import SingleTurnSample

sample = SingleTurnSample(
    response="""
        SELECT p.product_name, SUM(oi.quantity) AS total_quantity
        FROM order_items oi
        JOIN products p ON oi.product_id = p.product_id
        GROUP BY p.product_name;
    """,
    reference="""
        SELECT p.product_name, COUNT(oi.quantity) AS total_quantity
        FROM order_items oi
        JOIN products p ON oi.product_id = p.product_id
        GROUP BY p.product_name;
    """,
    reference_contexts=[
        """
        Table order_items:
        - order_item_id: INT
        - order_id: INT
        - product_id: INT
        - quantity: INT
        """,
        """
        Table products:
        - product_id: INT
        - product_name: VARCHAR
        - price: DECIMAL
        """
    ]
)

scorer = LLMSQLEquivalence()
scorer.llm = openai_model
await scorer.single_turn_ascore(sample)