用pytest插件把评测用例接入Phoenix实验记录

该资料介绍Phoenix的pytest插件,它把普通pytest测试映射为Phoenix数据集与实验运行。资料区分硬性不变量与质量信号两类检查,并说明标记、输出记录、LLM评审、重复运行和xdist并行等配置方式。

Phoenix pytest 插件将您测试套件与评估管道之间的间隙连接起来。 您将评价写为正常 `pytest` 菲尼克斯将每个案例记录为一次实验,以便你能够随着时间跟踪质量。当测试通过时,菲尼克斯将记录下来。 `pass=True`当它失败时, `pass=False`。由于插件会钩入 pytest 自己的退出代码, 您现有的 CI 闸门在没有任何额外配置的情况下工作 。 ## 何时使用 pytest 插件 凤凰也出价 [`run_experiment`](<https://arize.com/docs/phoenix/datasets-and-experiments/how-to-experiments/running-experiments>) 用于评价一个包含一个单一任务和一组共享评价员的完整数据集。 - **每个案件都需要不同的逻辑。** `run_experiment` 当您的系统子集需要不同的输入、设置或度量标准时,单独的测试功能比一个分支任务更容易表达。 - **你想表达强烈的期望。** 测试将 eval 变成二进制门: 失败 `assert` 失败 pytest 项, 失败 运行, 和 CI 失败 —— 和任何其他破损的测试完全一样 。 - **你已经使用pytest。** 在不改变运行方式的情况下, 将凤凰追踪添加到已有的套件中, 并保留 `pytest` 诸如固定装置等特征, `parametrize`, `-k` 过滤, `pytest-xdist`,以及 `pytest-asyncio`. 对于大型的,同质的数据集,每个例子都以同样的方式得分,更喜欢 `run_experiment` ——它将工作平行,使每个实验及其数据集易于管理. ## 如何运作 每个标记测试套件地图到 a **凤凰网数据集**。每个参数化测试案例图到一个 **数据集示例**。每套套房的运行都会产生新的 **实验** 断言结果——测试是否通过或失败? `pass` 实验运行时的注释 。 任何附加的分数都会成为他们自己的名注 。 ``` pytest test file → Phoenix dataset parametrize case → dataset example test run → experiment run assert outcome → "pass" annotation log_evaluation() → named annotation ``` 这意味着一个相同的套房, 打开你的拉请求 也构建了一个版本的历史 在凤凰城你可以比较 一段时间。 ## 两种检查: 变化无常对信号 在找到一个帮助者之前, 确定每个检查 *为:*. Evals与普通测试不同,因为LLM在循环中:输出是非决定性的,有些完全不能通过代码进行分级,而通过/失败往往太钝——质量生活在一个谱面上。这把每个检查推到两个桶中,而你对它们作不同的处理。 - **坚固无常者.** 完全有一个可接受的行为,普通代码可以验证它——一个要求拒绝,有效的JSON,一个必须调用的工具。 `assert`失败的断言记录 `pass=False` 并且将 CI 变为红色, 和任何单位测试完全一样。 如果变化的断裂, 构造断裂 。 - **质量信号.** 没有单一的正确字符串,只有更好和更糟糕的答案——帮助、立足、语气。 *分数* 这些(通常由LLM法官)而不是在他们身上坚持,而是在凤凰城看趋势。 单一的微弱结果不应该使建设失败,因为有些差异是模型的性质。 `log_evaluation()` / `evaluate()` 并将其作为说明加以累积;对总趋势的大门,而不是对每个案例的大门。 决定哪些检查是变化无常的,哪些是信号是真正的第一个动作——它之后的一切都是管道。一个很好的拇指规则: `assert` 将Fuzier 的东西评为信号。 ``` @pytest.mark.phoenix(dataset="my-first-eval") def test_first_eval(): output = run_system(scenario) # scenario through the system under test log_output({"response": output}) score = judge(output) # quality signal → record and trend log_evaluation(name="quality", score=score) assert invariant_holds(output) # hard invariant → gate CI ``` ## 安装 要求 **`arize-phoenix-client>=2.10.0`** ——介绍该词的版本. `@pytest.mark.phoenix` 插件 。 插件飞船 `arize-phoenix-client`。安装它与 `pytest` 额外 : ``` pip install "arize-phoenix-client[pytest]>=2.10.0" pytest ``` 如果您的评估人员使用 `arize-phoenix-evals`中,添加该额外内容: ``` pip install "arize-phoenix-client[pytest,evals]>=2.10.0" pytest ``` pytest通过插件的切入点自动发现插件——没有 `conftest.py` 需要设置。 ## 你的第一个Eval套房 以下是一个评价答题功能的最小例子: ``` import pytest from phoenix.client.pytest import log_output, log_evaluation @pytest.mark.phoenix(dataset="qa-suite") @pytest.mark.parametrize( "question,expected", [ ("What is the capital of France?", "Paris"), ("What is 12 multiplied by 8?", "96"), ("Who wrote Hamlet?", "Shakespeare"), ], ids=["geography", "arithmetic", "literature"], ) def test_answers(question, expected): result = my_app(question) log_output(result) assert result == expected ``` 使用您的凤凰网连接集运行 : ``` export PHOENIX_ENDPOINT=https://your-phoenix-host export PHOENIX_API_KEY=your-api-key # if required pytest tests/evals/test_qa.py ``` 那个... `ids` 您可以提供给 `parametrize` 重要:它们给每个案例一个 **稳定身份**。将每例的套件映射回同一个数据集实例,从而通过对一组固定实例的实验进行累积,而不是创建重复。 ## 那个... `@pytest.mark.phoenix` 标记 标记是指示测试的插件。 测试没有正常运行, 并且是凤凰城所看不见的 。 ``` @pytest.mark.phoenix( dataset="my-eval-suite", dataset_description="Customer support regression cases", experiment_description="GPT-4.1 with a lower temperature", experiment_metadata={ "model": "gpt-4.1", "parameters": {"temperature": 0.2}, }, evaluators=[correctness_evaluator], repetitions=3, ) def test_my_feature(input, expected): ... ``` | 参数 | 说明 | | --- | --- | | `dataset` | 凤凰城数据集和实验的名称。 省略时默认测试文件的相对路径 。 | | `dataset_description` | 描述存储在凤凰城数据集. | | `experiment_description` | 描述存储在凤凰号实验上. | | `experiment_metadata` | 元数据存储在实验上,如模型和引用参数. | | `evaluators` | 自动对抗每个案件的评估人员名单。 | | `repetitions` | 运行每个案例 多次衡量非决定主义。 | 确定同一数据集的测试必须使用匹配的非空描述和实验元数据。插件还添加了当前 Git 承诺 。 `git_sha` 当它运行在 Git 检查中时。设置 `git_sha` 输入 `experiment_metadata` 以记录不同的修订,例如您 CI 环境提供的承诺。 ### 数据集命名 省略时 `dataset=`,插件使用测试文件相对于您的工程根的路径——例如 `tests/evals/test_sql` ——因此不同文件中的测试成为单独的数据集,两个文件共享一个基名从未碰撞. 数据集名称的全优先顺序是: 1. `PHOENIX_TEST_DATASET` 环境变量( 最高 —— 压倒一切 ) 2. `phoenix_dataset` 输入 `pytest.ini` 3. 标记的 `dataset=` 关键字参数 4. 文件路径( 默认) ## 记录产出和评价 ### `log_output(value)` 记录当前运行的 system-under-test 输出。 传递任何 JSON 序列大小的操作 — 字符串、 dict 或列表。 因为 pytest 警告测试返回非 。`None` 值,您将把输出传递给此助手而不是返回它。 ``` def test_summarize(document, expected_summary): summary = summarizer(document) log_output({"summary": summary}) assert len(summary) < len(document) ``` ### `log_evaluation(name, score, label?, explanation?)` 在当前运行中记录一个命名的分数。 使用此选项来附加您在行中计算的任何度量 : ``` def test_answers(question, expected): result = my_app(question) log_output(result) exact = float(result.strip().lower() == expected.strip().lower()) log_evaluation(name="exact_match", score=exact, label="correct" if exact else "wrong") assert result == expected ``` ### `evaluate(evaluator, **kwargs)` 运行一个可调用的评价员并记录其结果作为注释。该函数返回评价员的结果,这样您就可以在它上进行单个测试: ``` def correctness(output, expected, **_): return {"name": "correctness", "score": float(output == expected)} def test_answers(question, expected): answer = my_app(question) log_output(answer) result = evaluate(correctness, output=answer, expected=expected) assert result["score"] == 1.0 ``` 失败的断言 : `evaluate()` 记录 `pass=False` 并失败 pytest 项——使评估者得分为 CI 门. 每一个分数从 `log_evaluation()`, `evaluate()`,而升起的标记评价员 被包裹在自己的 **评价员的跨度**,所以LLM-as-judge的调用与测试任务是分开的,注释直接链接到生成它的痕迹。您不需要单独的“跟踪反馈”上下文 — — 分离是自动的。点击凤凰城UI中的任何注释来打开评估者的痕迹。 ## 使用预建的凤凰城评估员 评估员从 `arize-phoenix-evals` 直接与 `evaluate()` 并且作为标注上的提升评价者: ``` import pytest from phoenix.client.pytest import evaluate, log_output from phoenix.evals import LLM from phoenix.evals.metrics import FaithfulnessEvaluator faithfulness = FaithfulnessEvaluator(llm=LLM(provider="openai", model="gpt-4o")) @pytest.mark.phoenix( dataset="rag-quality", evaluators=[faithfulness], ) @pytest.mark.parametrize( "input,context,answer", [ ("Where is the Eiffel Tower?", "The Eiffel Tower is in Paris.", "It is in Paris."), ("What is the longest river?", "The Amazon is the longest river.", "The Nile."), ], ids=["faithful", "unfaithful"], ) def test_rag_answers(input, context, answer): log_output(answer) # The faithfulness evaluator runs automatically after every case ``` 使用与下列方法相同的适配器来调用受控评价员: `run_experiment`,所以你为另一部作品撰写的评测员。 **按参数名称**: | 评估参数 | 来源 | | --- | --- | | `output` | 你所传递的 `log_output` | | `input` | 测试的虚化场作为映射 | | `expected` / `reference` | 同名参数化字段( 如果存在) | | `metadata` | 同名参数化字段( 如果存在) | | `trace_id` | 测试运行的跟踪编号 | 任何来自 [`arize-phoenix-evals`](<https://arize.com/docs/phoenix/evaluation/pre-built-metrics>) 在这里工作... `FaithfulnessEvaluator`, `RetrievalRelevanceEvaluator`,QA的正确性,毒性,以及更多,就像你传递给任何简单的功能一样。 `run_experiment`写一个自定义评价员一次,然后从两者中都使用。 ## LLM - as-a-judge : 评分质量信号 当支票是 [质量信号](<https://arize.com/docs/phoenix/evaluation/integrations/pytest#two-kinds-of-checks-invariants-vs-signals>) 准确性、帮助性、语气 — — 没有一条正确的线条可以与之相对立。 将判断权交给另一个模型。 [`create_classifier`](<https://arize.com/docs/phoenix/evaluation/how-to-evals/custom-llm-evaluators>),它发出一个映射到数值分数的标签,并附加一个解释。 `evaluate()` 并且判决被记录为它自己的注释 在一个相连的评价员范围下—— **不含** 因此,在凤凰城,一个单一的微弱的答案而不是打破建筑。 法官只读到它需要分级的内容 — — 问题和机器人的回答 — — 所以, `kwargs` 你转过身来 `evaluate()` 的模板变量。考虑一个支持的机器人,有两个任务可以清晰地映射到两种检查。对于一个问题,它可以回答,答案应该很有帮助。 *质量信号*,因为一个好的答案可以用十几种方式表达。对于一个非专题问题,它应该用固定的直线(a)表示。 *硬无变体*因此,我们判断对应答案件是否有帮助,并坚决拒绝: ``` import time import pytest from phoenix.client.pytest import evaluate, log_evaluation, log_output from phoenix.evals import LLM, create_classifier # The judge runs on its own model, configured independently of the bot under # test. It reads just the question and response; the kwargs to evaluate() below # fill these template variables. helpfulness = create_classifier( name="helpfulness", llm=LLM(provider="anthropic", model="claude-sonnet-4-6"), prompt_template=( "Question: {{question}}\n\nResponse: {{response}}\n\n" 'Label the response "helpful" if it accurately and directly answers the ' 'question, or "unhelpful" if it is wrong, vague, or off-topic.' ), choices={"helpful": 1.0, "unhelpful": 0.0}, ) CASES = [ ("How do I get a refund?", False), ("What's the capital of France?", True), # off-topic → must refuse ] @pytest.mark.phoenix(dataset="support-bot") @pytest.mark.parametrize("question,expect_refusal", CASES, ids=["refund", "offtopic"]) def test_support_response(question, expect_refusal): t0 = time.perf_counter() response = answer_question(question) log_output({"response": response}) # Structural metric, logged as a CODE annotation — a signal, not a gate. log_evaluation(name="latency_ms", score=(time.perf_counter() - t0) * 1000) if expect_refusal: # Hard invariant — the one behavior we refuse to ship broken. assert "I don't have information on that" in response else: # Quality signal — judged, NOT asserted. Helpfulness only means something # for answerable questions, so the judge runs here and trends in Phoenix. evaluate(helpfulness, question=question, response=response) ``` 这就是整个模式:判断质量有意义的案件,让得分累积成为趋势,同时 `assert` 将CI锁在法官身上——当一个无常的人真的需要LLM来验证时——捕捉结果并断言: `result = evaluate(judge, ...); assert result["score"] == 1.0`少用这个,因为它使非决定性的得分成为硬门。 给答案分级 *已锁定* 在检索到的上下文中(而不是仅仅在专题上),给予法官这种上下文——增加: `{{context}}` 变量到模板并通过 `context=...` 改为: `evaluate()`,或用于预建的 [`FaithfulnessEvaluator`](<https://arize.com/docs/phoenix/evaluation/pre-built-metrics>)。见 [RAG评价](<https://arize.com/docs/phoenix/evaluation/how-to-evals/custom-llm-evaluators>) 为完整的图案。 法官以自己的模式运行,独立于测试中的系统。 [配置法官 LLM](<https://arize.com/docs/phoenix/evaluation/how-to-evals/configuring-the-llm>) 如何选择和调谐它。 ## 重复 多次运行每个大小写, 以测量LLM输出中的非决定性。 每次重复都是单独的 pytest 项—— 可见 `-k`, `pytest-xdist`,还有你的IDE—— 和凤凰城的单独实验。凤凰城比较了它们。 ``` @pytest.mark.phoenix(dataset="creative-writing", repetitions=5) @pytest.mark.parametrize("prompt", ["Write a haiku about autumn."]) def test_haiku_quality(prompt): poem = my_llm(prompt) log_output(poem) score = evaluate_poem_quality(poem) log_evaluation(name="quality", score=score) assert score >= 0.6 ``` 决议顺序 `repetitions`: 每一次测试标记参数 + `PHOENIX_TEST_REPETITIONS` (原始内容存档于2019-09-31) (中文(简体) ). Env var – `1`. ## 环境变量 该插件完全通过环境变量配置,因此同一套件在本地开发中和在CI中可以有不同的行为,而无需更改代码. | 变量 | 默认 | 说明 | | --- | --- | --- | | `PHOENIX_TEST_TRACKING` | `true` | 主开关 设定为 `0` 或 时 间 `false` 运行下线——测试执行,但没有任何信息发送到凤凰城. | | `PHOENIX_TEST_REPETITIONS` | `1` | 每个标记测试默认重复 。 | | `PHOENIX_TEST_DATASET` | *(文件路径)* | 覆盖所有收集测试的数据集名称 。 | | `PHOENIX_ENDPOINT` | — | 你的凤凰城服务器 URL. | | `PHOENIX_API_KEY` | — | 凤凰城的"熊牌" | | `PHOENIX_CLIENT_HEADERS` | — | 可选的 JSON 头条转发给凤凰客户端. | 在当地不录下任何内容: ``` PHOENIX_TEST_TRACKING=0 pytest tests/evals/ ``` 当跟踪被关闭时,重复性仍然在扩大——对当地表面的片面故障有用。 ## 与 pytest- xdist 并行运行 该插件支持 `pytest -n auto`控制器创建了数据集和实验,并向工人分发其身份证明,并同时进行记录。无论工人人数多少,都创造了一个实验。 ``` pip install pytest-xdist pytest -n auto tests/evals/ ``` ## 做其他的火药 标记的设计是为了避开你的方式——你已经使用的工具继续工作: - **Async测试.** `async def` 测试没有改变 `pytest-asyncio` (或 减) `anyio`。 内置线性 `evaluate()` 在同声测试中工作,包括与同声评估员一起工作——结果记录的方式与同步测试相同。 - **固定装置和 `parametrize`.** 照常使用,每个 `parametrize` 大小写成为它自己的数据集实例; 使大小写稳定 `ids` 所以重新运行地图回到同一个例子。 - **专注和跳过.** 过滤器为 `-k`,选择标记 `-m`,或跳过 `@pytest.mark.skip` / `pytest.skip()`。跳过的案件完全没有记录;只有过滤过的运行 *附录* 到数据集(见 [数据集如何保持同步](<https://arize.com/docs/phoenix/evaluation/integrations/pytest#how-the-dataset-stays-in-sync>)). - **观察模式。** `pytest-watch` (`ptw`) 重运行保存。 `PHOENIX_TEST_TRACKING=0` 避免在每一个键盘上做一个实验。 ``` import pytest from phoenix.client.pytest import evaluate, log_output @pytest.mark.phoenix(dataset="qa-suite") @pytest.mark.parametrize("question,expected", [("Capital of France?", "Paris")]) async def test_async_answers(question, expected): answer = await my_async_app(question) # async task log_output(answer) result = evaluate(my_async_evaluator, output=answer, expected=expected) # async evaluator assert result["score"] == 1.0 ``` ### 配置数据集名称 `pytest.ini` 在不编辑测试或导出env var的情况下,为整个项目定下数据集名称,设置 `phoenix_dataset` ini 选项 : ``` # pytest.ini [pytest] phoenix_dataset = sql-app-evals ``` `PHOENIX_TEST_DATASET` 仍然优于ini选项,而ini选项又优于标记 `dataset=` (见 [数据集命名](<https://arize.com/docs/phoenix/evaluation/integrations/pytest#dataset-naming>)). ## 数据集如何保持同步 在一个 **全程运行** (没有路径过滤器),插件 *更新* 以精确地匹配所收集的病例的数据集,为已不存在的测试查找实例。 **部分运行** (与 `-k`, `-m`,文件,或 `::node` 过滤器,仅插件 *附录*,将未选择的示例保留在原位。 `pytest tests/evals/test_sql.py` 从删除您的其他数据集中删除。 写两首全集 **同一数据集名称同时** 例如,并行的CI 任务没有设置 `PHOENIX_TEST_DATASET` ——可以举出彼此的例子。对于真正同时从事的工作,请给出各自的名字: ``` PHOENIX_TEST_DATASET=evals-${GIT_BRANCH} pytest tests/evals/ ``` ## 使用 GitHub 动作 Gating CI 不需要额外的配置来使用 pytest 作为 CI 门: pytest 退出代码是 `1` 当任何测试失败时, `0` 当全部通过时 。 LLM 质量的回归会像一个中断的导入一样失败 。 ``` name: eval-ci on: pull_request: jobs: evals: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: python-version: "3.12" - run: pip install "arize-phoenix-client[pytest,evals]" pytest - name: Run eval suite env: PHOENIX_ENDPOINT: ${{ secrets.PHOENIX_ENDPOINT }} PHOENIX_API_KEY: ${{ secrets.PHOENIX_API_KEY }} run: pytest tests/evals/ ``` 上传到凤凰城最成功,也永远不会失败测试。 网络问题被报告为警告而不是失败建设,因此短暂的凤凰城停电不会阻碍您的部署。 ## 完整实例 包含内置评价的全文本到 SQL eval 套件 , 提升评价员, 以及 CI 准备结构 : ``` import pytest from phoenix.client.pytest import evaluate, log_evaluation, log_output # --- evaluators --- def valid_sql(output, **_): import sqlparse try: sqlparse.parse(output["sql"]) return {"name": "valid_sql", "score": 1.0, "label": "valid"} except Exception: return {"name": "valid_sql", "score": 0.0, "label": "invalid"} def token_f1(output, expected, **_): pred_tokens = set(output["sql"].lower().split()) ref_tokens = set((expected or {}).get("sql", "").lower().split()) if not ref_tokens: return {"name": "token_f1", "score": 0.0} precision = len(pred_tokens & ref_tokens) / len(pred_tokens) if pred_tokens else 0 recall = len(pred_tokens & ref_tokens) / len(ref_tokens) f1 = 2 * precision * recall / (precision + recall) if (precision + recall) else 0 return {"name": "token_f1", "score": f1} # --- test suite --- CASES = [ { "input": "Show all users", "expected": {"sql": "SELECT * FROM users;"}, "id": "select-all", }, { "input": "Count active subscriptions", "expected": {"sql": "SELECT COUNT(*) FROM subscriptions WHERE status = 'active';"}, "id": "count-active", }, { "input": "Top 5 customers by revenue", "expected": {"sql": "SELECT customer_id, SUM(amount) AS revenue FROM orders GROUP BY customer_id ORDER BY revenue DESC LIMIT 5;"}, "id": "top-customers", }, ] @pytest.mark.phoenix( dataset="text-to-sql", evaluators=[valid_sql, token_f1], ) @pytest.mark.parametrize( "input,expected", [(c["input"], c["expected"]) for c in CASES], ids=[c["id"] for c in CASES], ) def test_text_to_sql(input, expected): sql = my_sql_generator(input) log_output({"sql": sql}) assert sql.strip().endswith(";"), "SQL must end with a semicolon" ``` 本地运行, 以验证一切, 然后再推动 : ``` PHOENIX_TEST_TRACKING=0 pytest tests/evals/test_sql.py -v ``` 然后在CI中,启用凤凰城并让分数累积: ``` pytest tests/evals/test_sql.py ``` 这页有用吗? [建议编辑](<https://github.com/arize-ai/phoenix/edit/main/docs/phoenix/evaluation/integrations/pytest.mdx>)提出问题

查看原始来源