)
Kestra AI Agent 编排实战从手写 Agentic Loop 到声明式自主智能体LLM Zoomcamp Module 3【免费下载链接】llm-zoomcampLLM Zoomcamp - a free online course about real-life applications of LLMs. In 10 weeks you will learn how to build an AI system that answers questions about your knowledge base. Register here 项目地址: https://gitcode.com/GitHub_Trending/ll/llm-zoomcamp本文围绕 LLM Zoomcamp Module 3AI Orchestration with Kestra第 6 课展开系统讲解 Kestra 中 AI Agent 的声明式编排方式如何用AIAgent插件替代手写的 agentic loop如何通过prompt、systemMessage、provider、tools、memory等配置块构建可自主决策的智能体并借助仓库中的4_simple_agent.yaml与5_web_research_agent.yaml两个真实 Flow 掌握从「简单文本摘要」到「自主联网研究并落盘报告」的完整实战路径最后给出 Agent 可用工具矩阵与可观测性配置方法。读完本文你将能够独立编写、导入并运行 Kestra 中的 AI Agent Flow并为构建多 Agent 系统打下基础。从手写 Agentic Loop 到 Kestra 的AIAgent插件在 Module 1 的 Agents 入门课 中你通过手写代码搭建过完整的 agentic loop一个while循环不断调用 LLM执行模型返回的工具调用再把结果回传给模型直到模型输出不再包含任何工具调用的最终答案才停止。这一模式是所有 Agent 框架的基石——LLM 负责决策「下一步做什么」循环负责「执行并反馈」。Kestra 的AIAgent插件把这个循环封装成了声明式配置。你只需要定义三件事目标goal通过prompt告诉 Agent 要完成什么任务工具tools列出 Agent 可以调用的工具集合可选的系统消息systemMessage定义 Agent 的角色与行为准则。之后由 Kestra 驱动整个循环、管理对话历史并把最终结果以任务输出task output的形式呈现。这意味着你不用再关心循环的终止条件、消息历史的拼接与维护等样板代码只需描述「做什么」而非「怎么做」。注意本课的所有 Flow 都使用{{ secret(GEMINI_API_KEY) }}引用密钥。在运行它们之前请先完成 环境配置Setup 中的设置步骤。示例 Flow 均使用 Gemini 作为底层模型但provider块支持几乎所有主流 AI 提供方——把io.kestra.plugin.ai.provider.GoogleGemini换成 OpenAI、Anthropic 或其他提供方的实现即可其余配置结构完全一致。仓库中的 docker-compose.yml 也展示了在 Kestra 服务级别配置 Gemini 的方式通过kestra.ai.gemini.model-name与kestra.ai.gemini.api-key指定默认模型。传统工作流 vs AI Agent 工作流Kestra 中两种编排范式的本质差异在于「执行路径由谁决定」。传统工作流Traditional Workflow步骤序列固定逻辑预先确定模型不参与路径决策tasks: - id: step1 type: Task1 - id: step2 type: Task2 - id: step3 type: Task3AI Agent 工作流Agent 根据目标自主决定做什么、按什么顺序做tasks: - id: agent type: io.kestra.plugin.ai.agent.AIAgent prompt: Research data engineering trends and create a report tools: - WebSearch - TaskExecution从源码结构看前者的tasks列表即执行顺序本身每一步都是确定性的而后者只有一个 Agent 任务真正的「任务序列」由 LLM 在运行时动态生成——这正是两者最直观的区别。何时使用 AI Agent选择哪种范式取决于任务的确定性使用 AI Agent 的场景步骤的确切序列事先无法预知决策依赖动态变化的信息需要适应意料之外的条件例如搜索无结果时改写查询重试。使用传统工作流的场景步骤确定且可重复合规性要求可精确审计的过程成本和延迟必须最小化。这一决策原则在 最佳实践课 中被进一步总结为固定的、可重复的 ETL 管道用传统工作流确定性、可预测、合规研究和分析类任务用 AI Agent能根据发现调整策略复杂的多步骤目标则用多 Agent 系统专业分工协作。AI Agent 的解剖核心配置块详解一个完整的AIAgent任务由若干配置块组成下面是一个可运行的完整示例对应文档中的example_agentid: example_agent namespace: zoomcamp tasks: - id: agent type: io.kestra.plugin.ai.agent.AIAgent # Defines the agents role and behavior systemMessage: | You are a data analyst. Analyze data and provide insights. # The actual task or question prompt: What are the top 3 trends in this data? # LLM provider configuration provider: type: io.kestra.plugin.ai.provider.GoogleGemini modelName: gemini-2.5-flash apiKey: {{ secret(GEMINI_API_KEY) }} # Tools the agent can use tools: - type: io.kestra.plugin.ai.tool.TavilyWebSearch apiKey: {{ secret(TAVILY_API_KEY) }} # Memory for context across executions memory: type: io.kestra.plugin.ai.memory.KestraKVStore memoryId: analyst_001各配置块的作用与要点配置块作用要点prompt本次执行要完成的具体任务或问题必填可使用 Pebble 模板语法注入输入如{{ inputs.text }}systemMessage定义 Agent 的角色与行为准则决定输出风格、处理流程与约束条件是控制 Agent 行为的关键providerLLM 提供方配置type指定提供方实现modelName指定模型apiKey引用密钥toolsAgent 可调用的工具列表每项由type标识部分工具还需额外配置如apiKey、imagememory跨执行保存上下文示例使用KestraKVStore配合memoryId标识记忆单元contentRetrievers内容检索器如TavilyWebSearch在生成前把检索结果注入上下文configuration插件级行为配置如logRequests、logResponses控制请求/响应日志outputFiles声明 Agent 产出的文件配合文件系统类工具将结果落盘并在输出中暴露关于provider本课示例统一使用io.kestra.plugin.ai.provider.GoogleGemini与gemini-2.5-flash模型。在 最佳实践课 中提到Gemini 2.5 Flash 对标准推理免费、成本更低适合大多数工作流需要更强推理能力的复杂 Agent 任务再升级到更高阶模型。注意密钥必须通过{{ secret(GEMINI_API_KEY) }}引用严禁把 API Key 明文写进 YAML 提交到 Git。简单 Agent 示例可控制长度与语言的多语摘要Flow 文件flows/4_simple_agent.yaml这个 Flow 演示了一个基础 AI Agent对给定文本生成可控制长度short/medium/long与语言7 种可选的摘要。它展示了四个关键能力如何结构化 Agent 提示词systemMessage明确角色、输出长度规则与防「水话」要求prompt只负责注入待处理内容如何链式串联多个 Agent 任务第二个 Agent 以第一个 Agent 的输出outputs.multilingual_agent.textOutput作为输入继续处理如何用pluginDefaults消除重复配置两个 Agent 共享同一套provider配置无需各自重复书写如何跟踪 token 用量做成本监控通过tokenUsage输出记录每次调用的输入/输出/总 token 数。输入定义Flow 定义了三个输入其中两个是下拉选择inputs: - id: summary_length displayName: Summary Length type: SELECT defaults: medium values: - short - medium - long - id: language displayName: Language type: SELECT defaults: en values: - en - fr - de - es - it - pt - ja - id: text type: STRING displayName: Text to summarize defaults: | Kestra is an open-source orchestration platform ...summary_length与language用SELECT类型约束取值范围并给出默认值text是自由文本默认填充了一段关于 Kestra 与 LLM Zoomcamp 的介绍文字便于直接运行验证。多语摘要 Agent- id: multilingual_agent type: io.kestra.plugin.ai.agent.AIAgent description: Generate summary in requested language and length systemMessage: | You are a precise technical assistant. Produce a {{ inputs.summary_length }} summary in {{ inputs.language }}. Keep it factual, remove fluff, and avoid marketing language. If the input is empty or non-text, return a one-sentence explanation. Output format guidelines: - For short: 1-2 sentences - For medium: 2-5 sentences - For long: 1-3 paragraphs prompt: | Summarize the following content: {{ inputs.text }}注意systemMessage中直接通过 Pebble 语法注入{{ inputs.summary_length }}与{{ inputs.language }}把用户输入动态拼进系统提示词同时用「保持事实、去掉水分、避免营销语言」「空输入返回一句解释」「按长度给出输出格式指南」等约束显著提升输出质量的可控性。链式第二个 Agent- id: english_brevity type: io.kestra.plugin.ai.agent.AIAgent prompt: | Generate exactly 1 sentence English summary of the following: {{ outputs.multilingual_agent.textOutput }}第二个 Agent 引用第一个 Agent 的textOutput输出生成一句英文极简摘要演示了 Agent 任务的链式依赖——Kestra 会自动等待上游任务完成再执行下游。成本监控token 用量日志- id: log_token_usage type: io.kestra.plugin.core.log.Log message: | Token Usage Summary: Multilingual Agent: - Input tokens: {{ outputs.multilingual_agent.tokenUsage.inputTokenCount }} - Output tokens: {{ outputs.multilingual_agent.tokenUsage.outputTokenCount }} - Total tokens: {{ outputs.multilingual_agent.tokenUsage.totalTokenCount }} English Brevity Agent: - Input tokens: {{ outputs.english_brevity.tokenUsage.inputTokenCount }} - Output tokens: {{ outputs.english_brevity.tokenUsage.outputTokenCount }} - Total tokens: {{ outputs.english_brevity.tokenUsage.totalTokenCount }}tokenUsage是AIAgent的标准输出之一包含inputTokenCount、outputTokenCount、totalTokenCount三个字段。将其打印到日志即可直观对比不同提示词设计下的成本这是后续优化提示词、控制成本的重要依据。pluginDefaults 消除重复pluginDefaults: - type: io.kestra.plugin.ai.agent.AIAgent values: provider: type: io.kestra.plugin.ai.provider.GoogleGemini modelName: gemini-2.5-flash apiKey: {{ secret(GEMINI_API_KEY) }}pluginDefaults为 Flow 中所有io.kestra.plugin.ai.agent.AIAgent类型的任务注入默认provider配置两个 Agent 任务因此无需重复书写模型与密钥配置如果某个任务需要覆盖在任务内显式声明即可。进阶示例自主联网研究的 Web Research AgentFlow 文件flows/5_web_research_agent.yaml这个 Flow 演示了 Agent 的自主工具使用你只指定目标Agent 自己决定何时搜索、搜索几次、如何组织报告、何时结束。其完整工作流程为接收研究提示例如「Latest trends in workflow orchestration」决定使用联网搜索工具收集信息评估搜索结果判断是否需要更多搜索可反复「搜索 → 评估 → 再搜索」直至满意把发现综合成结构化的 Markdown 报告执行摘要 / 关键发现 / 详细分析 / 来源列表用文件系统工具把报告保存为research_report.md。输入与核心 Agent 配置inputs: - id: research_topic type: STRING displayName: Research Topic defaults: | Research the latest trends in data orchestration and workflow automation. Include information about: - Popular tools and platforms - Emerging patterns (e.g., AI-driven orchestration) - Key challenges in the space - Recent innovations tasks: - id: research_agent type: io.kestra.plugin.ai.agent.AIAgent description: Autonomous research agent with web search capabilities provider: type: io.kestra.plugin.ai.provider.GoogleGemini apiKey: {{ secret(GEMINI_API_KEY) }} modelName: gemini-2.5-flash prompt: {{ inputs.research_topic }} systemMessage: | You are a thorough research assistant. Follow this process: 1. Use the TavilyWebSearch content retriever to gather up-to-date information on the topic. Search multiple times if needed to get comprehensive coverage. 2. Evaluate the search results and determine if you have enough information. If not, search again with refined queries. 3. Synthesize your findings into a well-structured Markdown report with: - Executive Summary (2-3 sentences) - Key Findings (3-5 bullet points) - Detailed Analysis (2-3 paragraphs) - Sources (list URLs of key references) 4. Save the final report as research_report.md in the /tmp directory using the filesystem tool. Important rules: - Always use the TavilyWebSearch content retriever to get current information - Do not make up or hallucinate information - Include specific examples and data points when available - Always save the final report to research_report.md using the filesystem tool.systemMessage是整个 Agent 行为的「剧本」它把研究流程拆成明确的步骤收集 → 评估 → 综合 → 保存并给出强约束必须联网、禁止编造、必须落盘。这里的关键设计是把「如何做」写进系统消息而prompt只携带目标。内容检索器与工具contentRetrievers: - type: io.kestra.plugin.ai.retriever.TavilyWebSearch apiKey: {{ secret(TAVILY_API_KEY) }} maxResults: 10 tools: - type: io.kestra.plugin.ai.tool.DockerMcpClient image: mcp/filesystem command: [/tmp] binds: [{{workingDir}}:/tmp] outputFiles: - research_report.mdcontentRetrievers配置TavilyWebSearch检索器需要TAVILY_API_KEY设置方式见 03-setup.md免费档每月 1,000 次搜索maxResults: 10限制每次搜索返回的条目数检索结果会在 LLM 生成前注入上下文。tools使用DockerMcpClient工具按需拉起mcp/filesystem镜像的 MCP 服务器通过binds: [{{workingDir}}:/tmp]把工作目录挂载为容器内/tmp从而让 Agent 获得「写文件」的能力。outputFiles声明research_report.md为产出文件执行完成后可在任务输出中访问。结果日志与 token 统计- id: log_report type: io.kestra.plugin.core.log.Log message: | ✅ Research completed! Report saved to: {{ outputs.research_agent.outputFiles[research_report.md] }} Agent made autonomous decisions about: - Which searches to perform - How many searches were needed - How to structure the report - When the task was complete Token usage: {{ outputs.research_agent.tokenUsage.totalTokenCount }} tokens日志清晰展示了 Agent 的自主决策点执行哪些搜索、搜索多少次、如何组织报告、何时算完成。这正是「你指定 GOALAgent 决定 HOW」的核心价值。Agent 可用工具矩阵Kestra 为 Agent 提供了一套开箱即用的工具集合覆盖联网检索、代码执行、Kestra 任务/流程调用与 MCP 接入等能力工具用途示例场景TavilyWebSearch联网搜索当前信息市场调研、新闻监测GoogleCustomWebSearch使用 Google Custom Search API 搜索Google 搜索CodeExecution通过 Judge0 安全运行代码数学计算、数据校验KestraTask执行任意 Kestra 任务基于 1000 Kestra 插件运行任务KestraFlow触发其他 Kestra Flow调用其他 Flow 实现模块化StreamableHttpMcpClient通过 HTTP/SSE 使用 MCP 服务器连接远程 MCP 服务器DockerMcpClient使用 Docker 中的 MCP 服务器按需通过 Docker 拉起 MCP 服务器StdioMcpClient通过 stdio 使用 MCP 服务器与外部系统集成AIAgent把另一个 Agent 用作工具多 Agent 系统、专业子 Agent其中DockerMcpClient在本课研究 Agent 中用于文件系统写入AIAgent工具则是构建多 Agent 系统的关键——详见 07-multi-agent.md 中的公司调研示例flows/6_multi_agent_research.yaml主分析 Agent 把研究 Agent 当作工具调用实现「职责分离」与「按需委派」。Agent 可观测性追踪每一次决策与每一分成本Kestra 为 Agent 执行提供完整的可观测性token 用量、工具执行、请求与响应日志、输出、执行耗时全部可见。执行记录中可以看到模型每一步的推理与决策过程便于理解 Agent 为何做出某个工具调用。需要更详细日志时通过configuration属性开启请求/响应级别的日志tasks: - id: research_agent type: io.kestra.plugin.ai.agent.AIAgent description: Autonomous research agent with web search capabilities provider: type: io.kestra.plugin.ai.provider.GoogleGemini apiKey: {{ secret(GEMINI_API_KEY) }} modelName: gemini-2.5-flash configuration: logRequests: true logResponses: true开启后每次 LLM 请求与响应都会被记录是排查「Agent 行为不符合预期」的首选手段。结合执行时间轴还可以定位每个 Agent 任务的耗时瓶颈多 Agent 场景下的执行耗时分布可参考 07-multi-agent.md 中的示例图。在 最佳实践课 中还给出了成本控制的系统建议从免费档开始学习、简单任务用更小/更便宜的模型、用maxOutputTokens限制响应长度、在执行的输出中持续监控 token 用量。运行前提与环境准备要运行本课的 Agent Flow需要先完成 03-setup.md 中的环境准备要点如下启动 Kestra需要 Docker 与 Docker Compose仓库根目录的03-orchestration模块自带 docker-compose.yml内含 Kestra 服务、PostgreSQL 存储与密钥环境变量注入执行docker compose up -d后通过 http://localhost:8080 访问 UI。获取 API KeyGemini API Key必填免费档够用但速率限制较低频繁运行可能遇到429 Resource Exhausted稍等重试或升级付费档Tavily API Key联网搜索类 Flow 需要免费档每月 1,000 次搜索。以环境变量注入密钥Kestra 从SECRET_前缀的 base64 编码环境变量读取密钥export GEMINI_API_KEYyour-gemini-api-key-here # required export SECRET_GEMINI_API_KEY$(echo -n $GEMINI_API_KEY | base64) # required export SECRET_TAVILY_API_KEY$(echo -n your-tavily-api-key-here | base64) # optional docker compose up -d在 Flow 中用{{ secret(GEMINI_API_KEY) }}引用调用secret()时省略SECRET_前缀。切勿把 API Key 提交到 Git。导入 Flow通过 API 导入默认账号为adminkestra.io/Admin1234!curl -X POST -u adminkestra.io:Admin1234! http://localhost:8080/api/v1/flows/import -F fileUploadflows/4_simple_agent.yaml curl -X POST -u adminkestra.io:Admin1234! http://localhost:8080/api/v1/flows/import -F fileUploadflows/5_web_research_agent.yaml也可以直接把 Flow YAML 复制粘贴进 Kestra UI。运行在 UI 中进入zoomcamp命名空间找到4_simple_agentFlow 点击 Execute可自定义输入或保留默认值随后依次运行5_web_research_agent并分析日志与输出文件。小结从「指定步骤」到「指定目标」本课的核心转变是传统工作流要求你预先写下每一步Task1 → Task2 → Task3而 AI Agent 工作流只要求你写下目标——Agent 基于 LLM 的推理自主决定工具调用序列、循环次数与终止时机。Kestra 的AIAgent插件把这一能力声明式化prompt定义目标systemMessage定义行为剧本provider定义模型tools/contentRetrievers定义能力边界memory定义跨执行上下文tokenUsage与configuration.logRequests则让每次决策和每分成本都透明可审计。在此基础上把AIAgent本身作为工具即可演进为分工协作的多 Agent 系统相关内容见 07-multi-agent.md。【免费下载链接】llm-zoomcampLLM Zoomcamp - a free online course about real-life applications of LLMs. In 10 weeks you will learn how to build an AI system that answers questions about your knowledge base. Register here 项目地址: https://gitcode.com/GitHub_Trending/ll/llm-zoomcamp创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考