尧图网站设计 尧图网站设计YAOTU DESIGN
ARTICLE DETAIL

资讯详情

深耕网站设计与一线实操的经验洞察。

PraisonAI TypeScript 概念实战:从 Single Agent 到多智能体编排的 Agent / Task / PraisonAIAgents 入门指南

PraisonAI TypeScript 概念实战:从 Single Agent 到多智能体编排的 Agent / Task / PraisonAIAgents 入门指南 PraisonAI TypeScript 概念实战从 Single Agent 到多智能体编排的 Agent / Task / PraisonAIAgents 入门指南【免费下载链接】PraisonAIPraisonAI — Hire a 24/7 AI Workforce. Stop writing boilerplate and start shipping autonomous self-improving agents that research, plan, code, and execute tasks. Deployed in 5 lines of code with built-in memory, RAG, and support for 100 LLMs.项目地址: https://gitcode.com/GitHub_Trending/pr/PraisonAIPraisonAI的 TypeScript 框架将单 Agent 执行、多 Agent 顺序协作、基于 Task 依赖的编排三大核心概念封装成Agent、Task、PraisonAIAgents三个开箱即用的类。本文以仓库内 examples/concepts 示例目录 下的官方概念示例为骨架结合框架源码逐步拆解每个示例的运行方式、配置含义与底层执行原理读完你就能用 5 行级代码在自己的 Node.js 项目中搭建起可运行的 Agent 工作流。概念示例目录速览PraisonAI TypeScript 包npm 包名praisonai见 package.json在examples/concepts/下提供了四个相互递进的概念示例文件核心概念对应章节single-agent.ts单 Agent 直接执行任务任务以纯字符串传入第 3 节multi-agent.ts多 Agent 按顺序协作结果通过{previous_result}传递第 4 节task-based-agent.ts使用Task声明依赖关系采用 hierarchical 模式编排第 5 节movie-script-agent.tsAgent 高级配置role/goal/backstory/markdown的完整演示第 6 节所有示例都遵循同一套编程模型先构造 Agent角色与指令→ 再构造 Task任务与产出描述→ 最后交给PraisonAIAgents编排执行并await start()。安装与运行环境准备按照 concepts README 的说明在任意 Node.js 项目中安装框架npm install praisonai安装完成后可直接用ts-node运行仓库中的任一示例# 运行单 Agent 示例 npx ts-node src/praisonai-ts/examples/concepts/single-agent.ts # 运行多 Agent 顺序协作示例 npx ts-node src/praisonai-ts/examples/concepts/multi-agent.ts # 运行基于任务依赖的编排示例 npx ts-node src/praisonai-ts/examples/concepts/task-based-agent.ts注意README 明确指出这些示例假设你已从 npm 安装praisonai包如果你直接在包源码目录内运行即本仓库场景import 语句会自动解析到本地包代码无需额外安装。示例均使用if (require.main module) main()的入口写法既可作为脚本直接运行也可被其他模块安全 import。Single Agent一行任务驱动的入门示例single-agent.ts 是最简形态Agent 只负责定义身份与指令任务以字符串数组直接传入编排器。import { Agent, PraisonAIAgents } from praisonai; async function main() { // 创建一个简单的 Agent不显式声明 Task 对象 const agent new Agent({ name: BiologyExpert, instructions: Explain the process of photosynthesis in detail., verbose: true }); // 将任务以字符串形式交给编排器 const praisonAI new PraisonAIAgents({ agents: [agent], tasks: [Explain the process of photosynthesis in detail.], verbose: true }); try { console.log(Starting single agent example...); const results await praisonAI.start(); console.log(\nFinal Results:, results); } catch (error) { console.error(Error:, error); } } if (require.main module) { main(); }这段代码揭示了两条核心 API 规则字符串任务自动归一化tasks既可以接收字符串也可以接收Task对象。从 team.ts 的TeamTask归一化逻辑可以看到字符串任务会被包装成内部任务结构name、prompt、status等字段齐全因此即使不创建Task实例也能获得完整的生命周期跟踪。返回有序结果数组start()返回Promiseany[]单 Agent 场景下results[0]即该 Agent 的最终输出。verbose: true在这里有两个作用既会在控制台打印任务执行过程也会在底层开启流式输出——从 Agent.execute 的实现 可以看到Agent 通过this.llm.streamText(...)流式生成文本并在verbose时把 token 实时写入process.stdout同时累加到this.result。Multi Agent多 Agent 顺序协作与{previous_result}传递multi-agent.ts 展示了框架的核心能力之一多个 Agent 按顺序接力前一个 Agent 的输出作为后一个 Agent 的输入。示例构造了 ResearchAgent → SummaryAgent → RecommendationAgent 的研究-总结-建议流水线import { Agent, PraisonAIAgents } from praisonai; async function main() { const researchAgent new Agent({ name: ResearchAgent, instructions: Research and provide detailed information about renewable energy sources., verbose: true }); const summaryAgent new Agent({ name: SummaryAgent, instructions: Create a concise summary of the research findings about renewable energy sources. Use {previous_result} as input., verbose: true }); const recommendationAgent new Agent({ name: RecommendationAgent, instructions: Based on the summary in {previous_result}, provide specific recommendations for implementing renewable energy solutions., verbose: true }); const praisonAI new PraisonAIAgents({ agents: [researchAgent, summaryAgent, recommendationAgent], tasks: [ Research and analyze current renewable energy technologies and their implementation., Summarize the key findings from the research., Provide actionable recommendations based on the summary. ], verbose: true, process: sequential // Agents will run in sequence, passing results to each other }); try { console.log(Starting multi-agent example...); const results await praisonAI.start(); console.log(\nFinal Results:); console.log(Research Results:, results[0]); console.log(\nSummary Results:, results[1]); console.log(\nRecommendation Results:, results[2]); } catch (error) { console.error(Error:, error); } } if (require.main module) { main(); }需要特别留意的两个细节process: sequential是默认值。从 TaskAgentTeam 构造函数 可见this.process config.process || sequential即不传该参数时默认按顺序执行示例显式写出是为了可读性。占位符{previous_result}指令文本中的{previous_result}会被前一个任务的输出替换。源码层面顺序执行会收集依赖任务的输出并注入提示词——见 Agent.execute 中 dependencyResults 的处理框架将前序结果拼接为Task N Result: ...并明确要求 Agent基于这些结果完成任务。这种模式适合上游产出物是下游唯一输入的线性流程结果数组的下标与任务声明顺序严格一致因此示例可以按results[0]、results[1]、results[2]分别读取。Task Based Agent用 Task 声明依赖用 hierarchical 模式编排当任务之间存在明确的产出物依赖而非简单的上一步结果承接时task-based-agent.ts 展示了更工程化的做法用Task对象显式声明dependencies并切换为process: hierarchical由 Manager LLM 统一调度。该示例模拟营养师生成菜谱 → 美食博主写博客的真实工作流import { Agent, Task, PraisonAIAgents } from praisonai; async function main() { // 1. 先创建带完整人设的 Agent const dietAgent new Agent({ name: DietAgent, role: Nutrition Expert, goal: Create healthy and delicious recipes, backstory: You are a certified nutritionist with years of experience in creating balanced meal plans., verbose: true, instructions: You are a professional chef and nutritionist. Create 5 healthy food recipes ... Format your response in markdown. }); const blogAgent new Agent({ name: BlogAgent, role: Food Blogger, goal: Write engaging blog posts about food and recipes, backstory: You are a successful food blogger known for your ability to make recipes sound delicious and approachable., verbose: true, instructions: You are a food and health blogger. Write an engaging blog post about the provided recipes. ... Use the following recipes as input: {recipes} Format your response in markdown. }); // 2. 再创建 Task 并声明依赖 const recipeTask new Task({ name: Create Recipes, description: Create 5 healthy food recipes that are both nutritious and delicious, expected_output: A list of 5 detailed recipes with ingredients and instructions, agent: dietAgent }); const blogTask new Task({ name: Write Blog Post, description: Write an engaging blog post about the provided recipes, expected_output: A well-structured blog post discussing the recipes and their health benefits, dependencies: [recipeTask], // 关键声明依赖 agent: blogAgent }); // 3. 交给编排器使用 hierarchical 模式 const praisonAI new PraisonAIAgents({ agents: [dietAgent, blogAgent], tasks: [recipeTask, blogTask], verbose: true, process: hierarchical }); try { const results await praisonAI.start(); console.log(\nFinal Results:); console.log(Recipe Task Results:, results[0]); console.log(\nBlog Task Results:, results[1]); } catch (error) { console.error(Error:, error); } } if (require.main module) { main(); }该示例承载了 READMETask Management小节的全部要点并与源码形成一一对应Task 依赖dependenciesblogTask声明依赖recipeTask框架据此做依赖解析与排序。对应 Task 类的 dependencies 字段。产出描述expected_output作为 Agent 系统提示词的一部分见 Agent 组装系统提示词处约束 Agent 只输出预期形态的结果。未指定时默认值为Complete the task successfully见 TaskConfig 定义。变量插值{recipes}blogAgent 指令中的{recipes}占位符由上游任务输出注入这与 multi-agent 示例的{previous_result}是同一套变量替换机制的不同写法。hierarchical 模式从 TaskAgentTeam.start 的分支逻辑 可以看到三种模式分别走不同执行路径parallel用Promise.all并发执行hierarchical走executeHierarchical()其余走executeSequential()。hierarchical 模式由 Manager Agent默认模型见 manager_llm 默认值也支持通过配置项覆盖决定任务分派。示例还附带了一段以process.env.LOGLEVEL debug控制的计时调试逻辑用于测量 Agent/Task/编排器初始化与总执行耗时——这是排查瓶颈在模型调用还是框架层的实用手段。Movie Script Agentrole/goal/backstory/markdown 的完整 Agent 配置concepts 目录 中的第四个示例 movie-script-agent.ts 展示了 READMEKey Features中Agent Configuration的完整用法——把角色、目标、背景故事、Markdown 输出全部配齐const scriptAgent new Agent({ name: ScriptWriter, role: Professional Screenwriter, goal: Write an engaging and creative movie script, backstory: You are an experienced screenwriter who specializes in science fiction scripts, instructions: Write a compelling movie script about a robot stranded on Mars. The script should include: 1. Scene descriptions 2. Character dialogue 3. Emotional moments 4. Scientific accuracy where possible 5. A clear three-act structure Format the output in proper screenplay format., verbose: true, markdown: true }); const praisonAI new PraisonAIAgents({ agents: [scriptAgent], tasks: [Write a movie script about a robot stranded on Mars], verbose: true }); const results await praisonAI.start(); console.log(results[0]); // 第一个结果即剧本全文与源码对照可以看到这些配置项的真实作用role/goal/backstory全部进入系统提示词。从 Agent 构造与系统提示词组装 可见提示词模板为You are ${name}, a ${role}. Your goal is to ${goal}. Background: ${backstory}并追加任务名称、描述与预期输出最后强制要求只输出预期产出不要附加解释。markdown: true对应 TaskAgentConfig 中的 markdown 字段用于声明输出采用 Markdown 格式。llm模型选择TaskAgentConfig支持llm?: string默认模型为gpt-5-nano见 Agent 默认 LLM可通过该字段切换任意受支持的模型。在自有代码中使用官方最小可运行模板README 的 Usage in Your Code 小节给出了一个不依赖任何示例文件、可直接复制进自己项目的模板这是理解三件套 API 最直接的入口import { Agent, Task, PraisonAIAgents } from praisonai; // 创建 Agent const agent new Agent({ name: MyAgent, role: Custom Role, goal: Achieve something specific, backstory: Relevant background, verbose: true }); // 创建 Task const task new Task({ name: my_task, description: Do something specific, expected_output: Expected result, agent: agent }); // 运行 const system new PraisonAIAgents({ agents: [agent], tasks: [task], verbose: true }); const result await system.start();这段模板与示例代码的差异点在于Task通过agent: agent显式绑定执行者。从 Task 类实现 可以看到Task持有agent引用执行阶段正是通过该引用调用agent.execute(task)见 parallel 分支若任务未绑定 Agent 且无默认代理框架会抛出 No agent assigned to task 错误。另外官方包从 src/index.ts 统一导出了Agent、AgentTeam、Agents、PraisonAIAgents、Router等符号——其中AgentTeam是当前推荐的编排类PraisonAIAgents为其向后兼容别名见 team.ts 中的别名声明。AgentTeam额外支持returnDict: true让start()返回以任务名为 key 的字典而非数组见 AgentTeamStartDictOptionsoutput预设silent | verbose | normal三种运行输出档位见 resolveOutputPreset。关键特性全景配置、任务管理与执行模式将 README Key Features 小节展开并与仓库证据对照可以整理出如下能力矩阵1. Agent 配置Agent Configuration配置项说明源码依据nameAgent 名称用于日志与结果标识TaskAgentConfigrole/goal/backstory角色、目标、背景拼接进系统提示词系统提示词组装instructions具体执行指令可含{变量}占位符各概念示例verbose调试模式打印执行过程并开启流式输出流式输出实现llm模型选择默认gpt-5-nanoAgent 默认 LLMmarkdown声明 Markdown 格式输出TaskAgentConfig.markdown2. 任务管理Task Management任务依赖Task.dependencies声明前置任务框架自动解析依赖顺序产出规格expected_output描述预期结果约束 Agent 输出形态Agent 指派Task.agent将任务绑定到具体执行者更完整的任务能力如callback、outputJson、maxRetries、onError、asyncExecution、condition条件路由等在 Task 类的字段清单 中均有定义本组概念示例只覆盖了最核心的子集。3. 执行模式Execution Modesprocess参数支持三档取值默认sequential对应 TaskAgentTeam 的分支执行模式行为典型场景sequential按声明顺序执行前序结果注入后续提示词研究→总结→建议等线性流水线parallel基于Promise.all并发执行所有任务相互独立的批量任务hierarchicalManager Agentmanager_llm可配统一调度分派任务存在依赖且需要智能排产4. 进程控制Process Controlverbose 日志贯穿 Agent 与编排器两个层级的调试输出错误处理示例统一使用try/catch捕获start()抛出的异常框架底层还提供maxRetries默认 3、timeout默认 30000ms等进程级配置见 process 模块的 ProcessConfig依赖解析dependencies驱动的拓扑排序保证产出物在消费前就绪。小结从概念示例到生产工作流examples/concepts的四个示例构成了 PraisonAI TypeScript 的完整入门路径先用single-agent.ts掌握Agent 字符串任务的最简调用再用multi-agent.ts理解顺序协作与{previous_result}传递继而通过task-based-agent.ts学会用Task声明依赖并切换到 hierarchical 编排最后以movie-script-agent.ts补齐 role/goal/backstory/markdown 等生产级配置。结合 Agent / Task / AgentTeam 的源码实现 与 AgentTeam 编排器你已具备把单 Agent 问答升级为多角色自主协作流水线的全部基础能力——这也是 PraisonAI 所倡导的用几行代码部署自主 AI 工作流在 TypeScript 生态中的标准落地方式。【免费下载链接】PraisonAIPraisonAI — Hire a 24/7 AI Workforce. Stop writing boilerplate and start shipping autonomous self-improving agents that research, plan, code, and execute tasks. Deployed in 5 lines of code with built-in memory, RAG, and support for 100 LLMs.项目地址: https://gitcode.com/GitHub_Trending/pr/PraisonAI创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表