实战指南:get_inferences 与 list_inferences 完整解析)
TensorZero 查询历史推理记录Historical Inferences实战指南get_inferences 与 list_inferences 完整解析【免费下载链接】tensorzeroTensorZero is an open-source LLMOps platform that unifies an LLM gateway, observability, evaluation, optimization, and experimentation.项目地址: https://gitcode.com/GitHub_Trending/te/tensorzeroTensorZero 是开源的 LLMOps 平台统一了 LLM 网关、可观测性、评估、优化与实验能力。在推理Inference产生之后我们常常需要回溯分析某个请求用了哪个变体、耗时多少、带有哪些标签、输出了什么内容甚至要为偏好优化如 DPO导出演示数据。本文以 查询历史推理记录文档 与 完整可运行示例 为骨架系统讲解如何通过 TensorZero Gateway 的POST /v1/inferences/get_inferences与POST /v1/inferences/list_inferences两个接口以及 Python SDK 中对应的get_inferences与list_inferences按 ID 检索、按标签/指标/时间过滤、分页排序地获取历史推理数据并结合仓库源码剖析其底层实现。读完本文你将能够独立搭建可运行的示例环境并用 HTTP 或 SDK 两种方式完成历史推理的检索、筛选与数据导出。背景为什么要查询历史推理记录每一次调用 TensorZero Gateway 完成推理后推理记录Inference会被持久化到可观测性后端默认是 ClickHouse示例环境使用 Postgres。这些历史记录可用于分析模型行为检查不同变体、不同参数temperature、max_tokens 等下的实际输出调试问题定位某次异常输出的具体输入、耗时ttft_ms、processing_time_ms与标签导出数据用于微调或优化例如提取demonstration人工标注输出作为偏好数据或用于 DPO 等偏好优化。除了 TensorZero UI 提供的可视化浏览与筛选界面TensorZero Gateway 还提供了两个编程式查询接口允许你把历史推理数据接入自己的分析管线、批处理任务或自动化的数据回流流程。环境准备运行完整示例示例代码位于 examples/docs/guides/observability/query-historical-inferences包含 Python SDK 脚本、curl 脚本、Docker Compose 编排与最小配置是一个开箱即用的学习环境。依赖与配置示例的 Python 依赖声明在 pyproject.toml[project] name tensorzero-examples-docs-guides-observability-query-historical-inferences version 0.0.0 readme README.md requires-python 3.10 dependencies [ tensorzero2025.8.3, ]核心依赖是tensorzeroPython 包版本要求2025.8.3。建议使用 uv 管理环境uv sync后即可运行示例脚本。示例配置文件 config/tensorzero.toml 非常精简只有一行注释原因是该示例直接使用了model_name快捷方式无需显式声明 model/variant 配置即可调用模型# Minimal configuration for querying historical inferences # This example uses the model_name shortcut (no explicit model/variant config needed)启动 Gateway、UI 与数据库docker-compose.yml 声明了四个服务注意该文件顶部明确标注这是为学习目的简化的示例生产部署请参考正式部署文档切勿直接用于生产服务镜像作用gatewaytensorzero/gateway推理与查询 API 入口监听3000端口挂载./config并以--config-file /app/config/tensorzero.toml启动uitensorzero/ui可视化界面监听4000端口通过TENSORZERO_GATEWAY_URL连接网关postgrestensorzero/postgres:17存储推理记录使用内置 cron 扩展cron.database_nametensorzerogateway-run-postgres-migrationstensorzero/gateway一次性任务在网关启动前执行--run-postgres-migrations完成数据库迁移关键环境变量environment: TENSORZERO_POSTGRES_URL: postgres://postgres:postgrespostgres:5432/tensorzero OPENAI_API_KEY: ${OPENAI_API_KEY:?Environment variable OPENAI_API_KEY must be set.}其中OPENAI_API_KEY通过${...:?}语法强制要求设置未设置时 Docker Compose 会直接报错。启动命令OPENAI_API_KEYsk-... docker compose up启动完成后Gateway 健康检查地址为http://localhost:3000/healthcompose 中通过 wget 探测该端点推理查询接口为http://localhost:3000/v1/inferences/...UI 界面为http://localhost:4000。说明示例 compose 使用 Postgres 作为存储生产环境通常使用 ClickHouse本文后续会说明两个后端在查询接口行为上的差异。按 ID 查询推理记录get_inferences当你已知推理 IDUUID时可以直接获取对应的推理记录。HTTPPOST /v1/inferences/get_inferencesTensorZero SDKclient.get_inferences(...)请求参数参数类型必填说明idsstring[]是要检索的推理 IDUUID列表function_namestring否按函数名过滤当可观测性后端是 ClickHouse 时加上该参数可以显著提升查询性能output_sourcestring否默认inference返回输出的来源取值见下output_source的三种取值inference返回模型原始输出demonstration返回人工策展的反馈输出没有演示反馈的推理会被忽略none返回不带输出的推理记录。demonstration模式还会附带dispreferred_outputs字段通过反馈标记为不偏好的输出该字段主要服务于偏好类优化如 DPO。请求示例Python SDKtensorzero_sdk.pyfrom tensorzero import TensorZeroGateway t0 TensorZeroGateway.build_http(gateway_urlhttp://localhost:3000) t0.get_inferences(ids[00000000-0000-0000-0000-000000000000])HTTPcurl -X POST http://localhost:3000/v1/inferences/get_inferences \ -H Content-Type: application/json \ -d {ids: [00000000-0000-0000-0000-000000000000]}响应结构StoredInference两个接口返回的响应都包含inferences数组元素类型为StoredInference其属性如下字段类型说明dispreferred_outputsarray通过反馈标记为不偏好的输出仅当output_source为demonstration时可用主要用于偏好优化如 DPOepisode_idstring该推理所属 EpisodeUUIDfunction_namestring被调用的函数名inference_idstring推理的唯一标识UUIDinference_paramsobject推理参数如 temperature、max_tokens 等inputobject提供的输入system prompt、messages 等outputvaries推理输出chat 类型为 content blocksjson 类型为 JSONprocessing_time_msinteger可选总处理耗时毫秒tagsobject与推理关联的键值标签timestampstring推理发生时间RFC 3339 格式ttft_msinteger可选首 token 耗时毫秒variant_namestring使用的变体名源码视角get_inferences 的实现该端点的处理逻辑位于 crates/tensorzero-core/src/endpoints/stored_inferences/v1/get_inferences.rs。核心实现get_inferences函数L25-L52有以下两个值得注意的设计空 ID 列表短路如果请求中ids为空直接返回空结果不会触达数据库源码注释If no IDs are provided, return an empty response。内部复用 list 查询按 ID 查询实际上是把ids作为ListInferencesParams的ids字段并设置limit: u32::MAX、offset: 0后调用底层统一的database.list_inferences(...)。也就是说get_inferences与list_inferences共享同一套数据库查询管道只是入口参数不同。对应单元测试同文件 L148-L191验证了有效 ID 会以limit u32::MAX、offset 0传递给数据库层空 ID 列表不会触发任何数据库调用output_source会原样透传给数据库Inference/Demonstration/None三种模式均有测试覆盖其中None模式下返回记录的output为None且dispreferred_outputs为空。带过滤器的推理列表查询list_inferences当需要按条件批量检索历史推理如找出某标签下所有耗时超过 5 秒的推理使用列表接口。HTTPPOST /v1/inferences/list_inferencesTensorZero SDKclient.list_inferences(requestListInferencesRequest(...))请求参数参数类型默认值说明afterstring-游标分页获取该 ID 之后不含的推理不能与before或offset同时使用beforestring-游标分页获取该 ID 之前不含的推理不能与after或offset同时使用episode_idstring-按 Episode IDUUID过滤filtersobject-高级过滤支持按指标、标签、时间、演示反馈过滤可用逻辑运算符and/or/not组合function_namestring-按函数名过滤ClickHouse 后端下有助于提升性能limitinteger20返回的最大结果数offsetinteger0分页偏移量order_byarray-排序条件可指定多个output_sourcestringinference返回输出的来源取值同get_inferencessearch_query_experimentalstring-全文搜索查询实验性功能可能触发全表扫描variant_namestring-按变体名过滤过滤器filters类型详解filters是一个可递归组合的InferenceFilter支持以下七种节点类型逻辑组合节点类型属性说明andchildrenInferenceFilter[]必填、type必须为and对多个过滤器取逻辑与orchildrenInferenceFilter[]必填、type必须为or对多个过滤器取逻辑或notchildInferenceFilter必填、type必须为not对单个过滤器取逻辑非叶子过滤节点类型属性说明boolean_metricmetric_name必填、type必须为boolean_metric、valueboolean必填按布尔指标过滤匹配true或falsedemonstration_feedbackhas_demonstrationboolean必填、type必须为demonstration_feedback按是否存在演示反馈过滤float_metriccomparison_operator必填取/////!、metric_name必填、type必须为float_metric、valuenumber必填按数值指标值过滤tagcomparison_operator必填取/!、key必填、type必须为tag、valuestring必填按标签键值过滤timecomparison_operator必填取/////!、timeRFC 3339 时间戳必填、type必须为time按时间戳过滤排序order_by选项order_by支持多个排序条件每个条件有三种类型类型属性说明metricby必须为metric、name指标名必填、direction默认descending可取值ascending/descending按指标值排序search_relevanceby必须为search_relevance、direction默认descending按搜索相关性排序需要search_query_experimentaltimestampby必须为timestamp、direction默认descending按创建时间戳排序请求示例以按标签过滤 limit为例。Python SDKtensorzero_sdk.pyfrom tensorzero import TensorZeroGateway, ListInferencesRequest, InferenceFilterTag t0 TensorZeroGateway.build_http(gateway_urlhttp://localhost:3000) t0.list_inferences( requestListInferencesRequest( filtersInferenceFilterTag( keymy_tag, valuemy_value, comparison_operator, ), limit10, ) )HTTPcurl -X POST http://localhost:3000/v1/inferences/list_inferences \ -H Content-Type: application/json \ -d { filters: { type: tag, key: my_tag, value: my_value, comparison_operator: }, limit: 10 }源码视角list_inferences 的实现与测试保障list_inferences处理器同样位于 get_inferences.rs它将请求转换为ListInferencesParams后调用数据库层。同文件内的单元测试L285-L472对以下行为做了严格验证默认分页未显式指定时limit使用数据库层的DEFAULT_INFERENCE_QUERY_LIMIT而非无上限查询自定义分页limit 50、offset 100会被精确透传组合过滤function_name、variant_name、episode_id会同时生效并透传给数据库排序透传order_by如按Timestamp降序会正确传递到查询参数空结果无匹配记录时返回空数组而非报错。这说明列表接口的过滤、分页、排序能力由请求参数到数据库查询参数之间有一套完整的、经过测试验证的映射逻辑你可以在请求中放心组合使用。端到端实战从打标签到查询的完整链路示例仓库提供了两套等价的完整流程脚本Python 版 tensorzero_sdk.py 与 Shell 版 curl.sh。两者都演示了三个步骤产生带标签的推理 → 按 ID 查询 → 按标签过滤列表。Python 版流程tensorzero_sdk.py 的核心逻辑from tensorzero import InferenceFilterTag, InferenceResponse, ListInferencesRequest, TensorZeroGateway t0 TensorZeroGateway.build_http(gateway_urlhttp://localhost:3000) # 1. Make an inference with a tag response t0.inference( model_nameopenai::gpt-5-mini, input{messages: [{role: user, content: Write a haiku about TensorZero.}]}, tags{my_tag: my_value}, # for filtering later ) assert isinstance(response, InferenceResponse) inference_id str(response.inference_id) print(fCompleted Inference: {inference_id}) # 2. Query the inference by ID get_response t0.get_inferences( ids[inference_id], output_sourceinference, ) print(fRetrieved {len(get_response.inferences)} inference(s) by ID) # 3. List inferences filtered by the tag list_response t0.list_inferences( requestListInferencesRequest( output_sourceinference, filtersInferenceFilterTag( keymy_tag, valuemy_value, comparison_operator, ), limit10, ) ) print(fFound {len(list_response.inferences)} inference(s) with tag my_tagmy_value)这段脚本揭示了查询功能的核心配合方式在推理请求时通过tags参数给推理打上键值标签之后即可用InferenceFilterTag精确回溯这批数据。model_nameopenai::gpt-5-mini使用的是model_name快捷方式无需在配置文件中显式声明模型即可完成推理调用这也是上文tensorzero.toml保持空配置的原因。Shell 版流程curl.sh 走的是 OpenAI 兼容接口 原始 HTTP 查询接口的组合步骤 1产生带标签的推理OpenAI 兼容接口INFERENCE_RESPONSE$(curl -s -X POST http://localhost:3000/openai/v1/chat/completions \ -H Content-Type: application/json \ -d { model: tensorzero::model_name::openai::gpt-5-mini, messages: [{role: user, content: Write a haiku about TensorZero.}], tensorzero::tags: {my_tag: my_value} }) INFERENCE_ID$(echo $INFERENCE_RESPONSE | jq -r .id)注意这里使用模型名tensorzero::model_name::openai::gpt-5-mini与自定义字段tensorzero::tags推理 ID 取自 OpenAI 兼容响应的id字段。步骤 2按 ID 查询curl -s -X POST http://localhost:3000/v1/inferences/get_inferences \ -H Content-Type: application/json \ -d { \ids\: [\$INFERENCE_ID\], \output_source\: \inference\ } | jq .inferences | length | Retrieved \(.) inference(s) by ID步骤 3按标签过滤列表curl -s -X POST http://localhost:3000/v1/inferences/list_inferences \ -H Content-Type: application/json \ -d { output_source: inference, filters: { type: tag, key: my_tag, value: my_value, comparison_operator: }, limit: 10 } | jq .inferences | length | Found \(.) inference(s) with tag my_tagmy_value运行方式需先启动 docker compose 并安装 jq./curl.sh # 或 python tensorzero_sdk.py进阶实践建议基于上文接口能力与源码实现以下几点值得在实际项目中应用善用标签体系在推理请求阶段就规划好tags如业务渠道、用户分组、实验名称之后即可用InferenceFilterTag做低成本的数据切片这是把可观测数据转化为可分析数据的最简路径。ClickHouse 后端下优先带function_name文档与接口参数说明都明确指出当可观测性后端为 ClickHouse 时传入function_name可提升查询性能利用其分区/主键结构。演示反馈数据的利用将output_source设为demonstration可获取人工标注输出与dispreferred_outputs这是构建 DPO 等偏好优化数据集的数据来源none模式则适合只需要元数据如统计耗时、标签分布的轻量查询。分页方式的选择小数据集可用offset/limit翻页对大规模数据推荐使用after/before游标分页两者不可混用after/before不能与offset同时使用。实验性全文搜索需谨慎search_query_experimental是实验功能可能触发全表扫描生产环境大规模数据下使用前应评估成本。小结TensorZero 将推理产生与推理回查统一在 Gateway 之上get_inferences面向按 ID 的精准检索list_inferences面向多维度的筛选、排序与分页两者共享底层的数据库查询管道并有完整的单元测试保障参数映射的正确性。结合 示例仓库 提供的 Python 与 Shell 两套可运行脚本你可以在几分钟内搭建起打标签 → 推理 → 按 ID 回查 → 按标签过滤的完整闭环为模型行为分析、问题排查与优化数据导出打下基础。若需在 UI 中进行交互式浏览筛选可参考 TensorZero UI 部署文档。【免费下载链接】tensorzeroTensorZero is an open-source LLMOps platform that unifies an LLM gateway, observability, evaluation, optimization, and experimentation.项目地址: https://gitcode.com/GitHub_Trending/te/tensorzero创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考