
adk-python 实战使用 BigQueryAI.FORECAST基于 TimesFM 构建免训练时间序列预测【免费下载链接】adk-pythonAn open-source, code-first Python toolkit for building, evaluating, and deploying sophisticated AI agents with flexibility and control.项目地址: https://gitcode.com/GitHub_Trending/ad/adk-pythonAI.FORECAST是 BigQuery 内置的 AI 函数借助预训练的TimesFM基础模型直接完成时间序列预测无需自行训练和管理模型。本文以 adk-python 仓库中随附的 BigQuery AI/ML Skill 文档为核心完整讲解其 SQL 语法、全部输入参数、动态输出 Schema并结合仓库源码说明如何在 ADK Agent 中通过bigquery-ai-mlSkill 与BigQueryToolset落地这一能力让 LLM Agent 能够自动读懂规范、生成并执行预测查询。背景为什么用 Skill 而非专用工具做预测在 adk-python 中BigQuery 相关的 AI/ML 功能遵循以 SQL Skill 优先的设计取向。SKILL.md 明确说明对于预测Forecasting、异常检测Anomaly Detection等能力Agent 应优先使用 Skill 中定义的标准 SQLAI.*函数通过execute_sql()执行而不是调用对应的高层专用工具。其原因在于AI.*系列函数参数丰富、语义灵活用标准 SQL 表达比封装成固定工具参数更通用、更贴近 BigQuery 原生能力。该 Skill 的 frontmatter 声明了它的元信息name: bigquery-ai-ml license: Apache-2.0 metadata: author: google-adk version: 1.0 description: | Skill for BigQuery AI and Machine Learning queries using standard SQL and AI.* functions (preferred over dedicated tools).SKILL.md 自身不内嵌这些函数的语法而是强制要求 Agent 在生成 SQL 前必须先读取对应的 reference 文件并明确警告不要猜测文件名。其中与本主题对应的映射为FunctionDescriptionRequired Reference FileAI.FORECASTTime-series forecasting via the pre-trained TimesFM modelreferences/bigquery_ai_forecast.md本文所讲解的 bigquery_ai_forecast.md 正是该 Skill 的强制参考文件之一是 Agent 生成预测 SQL 时的事实标准。AI.FORECAST语法总览AI.FORECAST的完整语法如下SELECT * FROM AI.FORECAST( { TABLE project.dataset.table | (QUERY_STATEMENT) }, data_col DATA_COL, timestamp_col TIMESTAMP_COL [, model MODEL] [, id_cols ID_COLS] [, horizon HORIZON] [, confidence_level CONFIDENCE_LEVEL] [, output_historical_time_series OUTPUT_HISTORICAL_TIME_SERIES] [, context_window CONTEXT_WINDOW] )几点关键结构说明第一个位置参数是数据源既可以传TABLE \project.dataset.table直接引用一张历史数据表也可以传(QUERY_STATEMENT) 形式的子查询作为输入data_col与timestamp_col使用命名参数语法传入是必填项其余全部为可选命名参数带方括号[, ...]标注可依据场景组合使用AI.FORECAST是表值函数table-valued function因此必须放在FROM子句中通过SELECT * FROM AI.FORECAST(...)消费其输出。输入参数详解ArgumentRequirementTypeDescriptioninput_dataRequiredThe source table or subquery containing historical data.data_colRequiredStringThe numeric column to predict.timestamp_colRequiredStringThe column containing dates/timestamps.id_colsOptionalArrayStringGrouping columns for multiple series (e.g.,[store_id]).horizonOptionalInt64Number of future points to predict. Defaults to 10. The valid input range is [1, 10,000].confidence_levelOptionalFloat64Confidence interval (0 to 1). Defaults to 0.95.modelOptionalStringModel version. Defaults toTimesFM 2.0.context_windowOptionalInt64The number of historical data points the model uses to forecast. The min value is 64 and the max value is 2048 forTimesFM 2.0. If not set, the model determines this automatically.对参数语义的进一步说明input_data历史数据来源要求至少包含一个数值列和一个时间/日期列。表或子查询中的时间点建议按时间升序排列以反映真实的时间序列走势data_col被预测的数值列即预测目标应为连续型数值如销售额、骑行次数timestamp_col时间戳列用于确定序列的时间步与粒度id_cols多序列分组键。当数据包含多个实体如多个门店、多个用户类型时通过该参数让模型为每个分组独立预测避免不同序列混在一起horizon预测未来多少个时间点默认 10合法范围为 [1, 10,000]confidence_level预测区间的置信水平取值 (0, 1)默认 0.95即默认给出 95% 预测区间model模型版本字符串当前默认TimesFM 2.0。TimesFM 是 Google 的预训练时间序列基础模型AI.FORECAST直接复用其能力无需训练context_window模型回溯使用的历史数据点数仅对TimesFM 2.0有效范围为 [64, 2048]不设置时由模型自动决定通常可忽略。输出 Schema随output_historical_time_series动态变化AI.FORECAST的输出列会随output_historical_time_series标志位调整这是使用时最需要注意的一点ColumnTypeIncluded if output_historical_time_seriesFALSEIncluded if output_historical_time_seriesTRUEDescriptionid_cols(As Input)YesYesOriginal identifiers for the series.forecast_timestampTIMESTAMPYesNoTimestamp for predicted points.forecast_valueFLOAT64YesNoThe 50% quantile (median) prediction.time_series_timestampTIMESTAMPNoYesUniform timestamp column for both history and forecast.time_series_dataFLOAT64NoYesMerged column: actual values for history, median for forecast.time_series_typeSTRINGNoYesLabel:historyorforecast.prediction_interval_lower_boundFLOAT64YesYesLower bound (NULL for historical rows).prediction_interval_upper_boundFLOAT64YesYesUpper bound (NULL for historical rows).confidence_levelFLOAT64YesYesThe constant confidence level used.ai_forecast_statusSTRINGYesYesError messages or empty string on success. A minimum of 3 data points is required.要点解读默认模式FALSE输出仅含预测点核心列是forecast_timestamp与forecast_value后者为 50% 分位数中位数预测历史回填模式TRUE输出将历史真实值与预测值合并到统一的time_series_timestamp/time_series_data列中并用time_series_type标记每一行是history还是forecast便于直接绘图或对比两类模式下都会输出prediction_interval_lower_bound、prediction_interval_upper_bound历史行取 NULL、固定的confidence_level以及ai_forecast_status——该列携带错误信息成功时为空字符串参考文档特别强调至少需要 3 个数据点才能执行预测这是ai_forecast_status可能报错的最低数据量门槛。完整示例基于 Citi Bike 数据的 30 天预测参考文档给出了一个可直接运行的完整示例——基于 BigQuery 公共数据集bigquery-public-data.new_york.citibike_trips按日期与用户类型聚合骑行次数再对每个用户类型分别预测未来 30 天WITH citibike_trips AS ( SELECT EXTRACT(DATE FROM starttime) AS date, usertype, COUNT(*) AS num_trips FROM bigquery-public-data.new_york.citibike_trips GROUP BY date, usertype ) SELECT * FROM AI.FORECAST( TABLE citibike_trips, data_col num_trips, timestamp_col date, id_cols [usertype], horizon 30, output_historical_time_series true);拆解这个示例可以看出完整的实战模式CTE 预处理先用WITH子查询把原始骑行记录按date和usertype聚合为每个用户类型每天的总骑行次数形成规整的时序数据数据源TABLE citibike_trips直接引用 CTE也可引用物理表或任意子查询目标列data_col num_trips指定被预测的数值列时间列timestamp_col date指定日期列由EXTRACT(DATE FROM starttime)生成多序列分组id_cols [usertype]让模型分别为 Subscriber、Customer 等用户类型独立建模预测预测长度horizon 30预测未来 30 天历史回填output_historical_time_series true让结果同时包含历史真实值标记为history与预测值标记为forecast便于一条 SQL 直接产出可对比、可绘图的时间序列。在 ADK Agent 中接入Skill BigQueryToolset 的落地方式AI.FORECAST的参考文档之所以被设计成 Skill 的强制 reference 文件是因为在 adk-python 中它最终由 LLM Agent 在推理时读取并转化为可执行 SQL。仓库为此提供了完整配套1. 预打包 Skill 的加载入口bigquery_skill.py 是预打包 Skill 的工厂函数它从仓库目录加载bigquery-ai-mlSkill_SKILL_DIR pathlib.Path(__file__).parent / skills / bigquery-ai-ml def get_bigquery_skill() - Skill: return load_skill_from_dir(_SKILL_DIR)其 docstring 给出了与SkillToolset、BigQueryToolset组合装配的推荐用法from google.adk.tools.bigquery import BigQueryToolset from google.adk.tools.bigquery.bigquery_skill import get_bigquery_skill from google.adk.tools.skill_toolset import SkillToolset bq_skill get_bigquery_skill() toolset SkillToolset(skills[bq_skill]) bigquery_toolset BigQueryToolset(...) agent LlmAgent(tools[bigquery_toolset, toolset])从源码结构看skill_toolset.pyAgent 运行时通过list_skills/search_skills/load_skill等工具发现并加载 Skill再用load_skill_resource读取references/bigquery_ai_forecast.md获取语法最后通过 BigQueryToolset 暴露的execute_sql()执行预测查询。SKILL.md中的Mandatory Reference Routing表格正是为了约束 Agent 必须按精确路径读取本文所讲的 reference 文件从机制上防止 LLM 幻觉出错误语法。2. 执行预测 SQL 的工具execute_sql()BigQueryToolset其正式实现在 integrations/bigquery/bigquery_toolset.pytools/bigquery/bigquery_toolset.py仅为迁移后的兼容转发层暴露了执行查询所需的核心工具。从get_tools()的注册列表可以看到除元数据查询外还注册了query_tool.get_execute_sql(...)作为通用 SQL 执行入口AI.FORECAST的 SQL 正是经由它提交到 BigQuery 执行funcs: list[Callable[..., Any]] [ metadata_tool.get_dataset_info, metadata_tool.get_table_info, metadata_tool.list_dataset_ids, metadata_tool.list_table_ids, metadata_tool.get_job_info, query_tool.get_execute_sql(self._tool_settings), query_tool.forecast, query_tool.analyze_contribution, query_tool.detect_anomalies, data_insights_tool.ask_data_insights, search_tool.search_catalog, ]3. 完整可运行的 Agent 样例仓库在 contributing/samples/integrations/bigquery/agent.py 提供了一个完整可参考的 Agent 装配样例涵盖凭据、工具配置与 Agent 定义三个层面from google.adk.agents.llm_agent import LlmAgent from google.adk.integrations.bigquery.bigquery_credentials import BigQueryCredentialsConfig from google.adk.integrations.bigquery.bigquery_toolset import BigQueryToolset from google.adk.integrations.bigquery.config import BigQueryToolConfig from google.adk.integrations.bigquery.config import WriteMode tool_config BigQueryToolConfig( write_modeWriteMode.ALLOWED, application_nameBIGQUERY_AGENT_NAME, max_query_result_rows50, ) bigquery_toolset BigQueryToolset( credentials_configcredentials_config, bigquery_tool_configtool_config ) root_agent LlmAgent( nameBIGQUERY_AGENT_NAME, description( Agent to answer questions about BigQuery data and models and execute SQL queries. ), instruction\ You are a data science agent with access to several BigQuery tools. Make use of those tools to answer the users questions. , tools[bigquery_toolset], )4. 相关配置项说明从 config.py 可确认与预测查询执行相关的关键配置及默认值write_mode默认WriteMode.BLOCKED即默认只允许只读SELECT操作预测类查询属于只读默认即可执行。样例中改为ALLOWED仅为演示全部能力生产环境建议保持默认或使用PROTECTEDmax_query_result_rows单次查询最多返回的行数默认 50AI.FORECAST输出行数较多时可适当调大maximum_bytes_billed查询计费上限受 BigQuery 按需计费规则约束必须 10,485,76010 MB可作为成本护栏locationBigQuery 区域未设置时按数据所在位置自动判定compute_project_id指定执行计算的项目可作为护栏防止工具在错误项目上产生开销job_labels/application_name用于作业追踪与标识其中adk-bigquery-前缀为内部保留。凭据方面样例演示了四种来源ADCApplication Default Credentials默认推荐、OAuth2 交互式授权需OAUTH_CLIENT_ID/OAUTH_CLIENT_SECRET环境变量、服务账号密钥文件、以及通过 ToolContext 注入的外部访问令牌external_access_token_key。使用建议与注意事项结合参考文档与仓库实现总结以下实操要点数据量下限ai_forecast_status明确要求历史数据至少 3 个数据点否则会返回错误信息生产场景建议提供远多于 3 个点的时间序列以获得可靠预测默认值认知horizon默认 10、confidence_level默认 0.95、model默认TimesFM 2.0在未显式指定时这些默认值生效context_window有界仅对TimesFM 2.0支持 [64, 2048] 范围不设置时由模型自动决定一般无需干预输出列差异务必根据output_historical_time_series的值预判结果列名——FALSE 模式读forecast_timestamp/forecast_valueTRUE 模式读time_series_timestamp/time_series_data/time_series_type两者共享区间列与ai_forecast_status免训练特性AI.FORECAST直接调用预训练 TimesFM 模型无需创建、训练或管理自定义模型显著降低时序预测的上手成本Agent 场景在 adk-python 中把本文对应的 reference 文件交给 Agent 读取再配合execute_sql()即可让 LLM 自主完成理解需求 → 生成预测 SQL → 执行并汇报的闭环如需引入 Skill请遵循 SKILL.md 中的强制路由规则不要猜测 reference 文件名。延伸阅读Skill 总览与强制路由表bigquery-ai-ml/SKILL.md本文主题参考文档bigquery_ai_forecast.mdSkill 加载与执行机制skill_toolset.pyBigQuery 工具集装配bigquery_toolset.py工具配置项定义config.py完整 Agent 样例contributing/samples/integrations/bigquery/agent.py【免费下载链接】adk-pythonAn open-source, code-first Python toolkit for building, evaluating, and deploying sophisticated AI agents with flexibility and control.项目地址: https://gitcode.com/GitHub_Trending/ad/adk-python创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考