Agno PostgreSQL 持久化实践指南:为 Agent、Team 与 Workflow 接入会话存储 Agno PostgreSQL 持久化实践指南为 Agent、Team 与 Workflow 接入会话存储【免费下载链接】agnoBuild, run, and manage agent platforms.项目地址: https://gitcode.com/GitHub_Trending/ag/agnoAgnoagno提供PostgresDb与AsyncPostgresDb两个数据库接口可将 Agent、Team团队与 Workflow工作流的运行会话、消息历史和记忆状态持久化到 PostgreSQL 中从而实现跨进程、跨重启的连续性对话。本文以仓库中的 cookbook/06_storage/postgres/README.md 为骨架结合源码与完整示例讲解同步/异步两种连接方式、三种调用主体的接入方法以及底层实现原理。读完你可以将任意 Agno 应用一键切换到 PostgreSQL 存储后端并在需要高并发时无缝升级到异步方案。为什么用 PostgreSQL 存储 Agno 会话Agno 应用默认的会话数据保存在内存中进程结束即丢失。给 Agent、Team 或 Workflow 挂载一个数据库后端后会话Session持久化每次运行Run的消息历史、运行状态与结果被写入数据库重启进程后可用原有session_id恢复对话历史上下文注入配合add_history_to_contextTrue模型在每轮生成前可读取历史消息实现多轮连续对话状态与记忆管理session、runs、memory 等表为 会话状态管理、记忆持久化 等高级能力提供落盘基础。相比同为 Agno 支持的 SQLite、MySQL、MongoDB 等后端见 cookbook/06_storage 目录PostgreSQL 提供成熟的表结构管理、事务保障与并发控制是生产环境最常见的选型之一。环境安装与依赖在同步场景中Agno 通过 SQLAlchemy 连接 PostgreSQL驱动使用psycopg2-binary。原文档给出的安装命令是uv pip install psycopg2-binary仓库中的示例脚本注释补充了运行所需的其他依赖例如 postgres_for_agent.py 头部注明uv pip install ddgs sqlalchemy openai其中ddgs与openai分别服务于示例中使用的WebSearchTools与 OpenAI 模型sqlalchemy是PostgresDb的核心依赖——在 libs/agno/agno/db/postgres/postgres.py 的源码中如果检测不到 SQLAlchemy会直接抛出ImportError并提示先安装。Team 示例 postgres_for_team.py 还需要newspaper4k与lxml_html_clean。异步方案则改用纯异步驱动psycopg依赖声明在 async_postgres/README.md 中uv pip install sqlalchemy psycopg注意同步与异步所用驱动与连接串协议不同psycopgvspsycopg_async请按需安装不要混用。同步接入PostgresDb 基本配置原文档给出的最小配置如下from agno.agent import Agent from agno.db.postgres import PostgresDb db PostgresDb(db_urlpostgresqlpsycopg://username:passwordlocalhost:5432/database) agent Agent( dbdb, add_history_to_contextTrue, )db_url遵循 SQLAlchemy 标准 URL 格式各段含义为片段说明postgresqlpsycopg使用 psycopgv3方言驱动的同步协议username:password数据库账号与密码localhost:5432主机与端口PostgreSQL 默认端口为 5432database目标数据库名需提前创建将数据库对象传入db参数后Agent 在每次运行时都会自动把本轮会话写入数据库。关键参数与底层行为对照 PostgresDb.init的源码构造函数还支持以下高频参数参数作用db_engine直接传入已有的 SQLAlchemyEngine与db_url二选一db_schema指定 PostgreSQL schema默认publicsession_table存储 Agent/Team/Workflow 会话记录的表名runs_table存储每次运行记录的表名memory_table存储用户记忆的表名knowledge_table存储知识库内容的表名traces_table/spans_table存储运行追踪 trace / span 的表名create_schema是否自动建表默认True若由外部迁移工具管理 schema 可设为False源码对连接建立顺序有明确约定优先使用传入的db_engine其次使用db_url二者皆缺则抛出ValueError。因此二选一传入即可。此外PostgresDb还支持将 session、runs、memory、metrics、eval、knowledge、traces、spans、learnings、schedules 等运行数据分表存储并内置了建表create_schema与 schema 管理能力具体表结构定义可查阅 libs/agno/agno/db/postgres/schemas.py。三份同步示例Agent、Team、Workflow原文档将示例分为三个文件分别覆盖 Agno 的三类执行主体。1. Agent多轮对话自动存档完整代码见 postgres_for_agent.pyfrom agno.agent import Agent from agno.db.postgres import PostgresDb from agno.tools.websearch import WebSearchTools db_url postgresqlpsycopg://ai:ailocalhost:5532/ai db PostgresDb(db_urldb_url) agent Agent( dbdb, tools[WebSearchTools()], add_history_to_contextTrue, ) if __name__ __main__: agent.print_response(How many people live in Canada?) agent.print_response(What is their national anthem called?)关键点连续两次提问第二次依赖历史上下文才能回答“their national anthem”指代的内容——这正是add_history_to_contextTrue配合db生效的体现示例使用localhost:5532端口本地搭建时需保证该端口的 PostgreSQL 实例可达并预先创建好ai数据库与账号。2. Team多智能体团队共享存储postgres_for_team.py 演示了将db挂载到Team上。示例构建了一个由 HackerNews 研究者与 Web 搜索者组成的团队并使用 pydantic 定义结构化输出Articlefrom agno.team import Team hn_team Team( nameHackerNews Team, modelOpenAIChat(gpt-5.6-luna), members[hn_researcher, web_searcher], dbdb, instructions[ First, search hackernews for what the user is asking about., Then, ask the web searcher to search for each story to get more information., Finally, provide a thoughtful and engaging summary., ], output_schemaArticle, markdownTrue, show_members_responsesTrue, ) if __name__ __main__: hn_team.print_response(Write an article about the top 2 stories on hackernews)这里的db复用方式与 Agent 完全一致说明PostgresDb 实例可被 Agent、Team 等对象共享团队内各成员的中间响应、团队会话记录都会通过同一存储后端落盘。该脚本的运行方式注释在文件头给出python cookbook/06_storage/postgres/postgres_for_team.py3. Workflow指定会话表的多步流程postgres_for_workflow.py 演示了 Workflow 场景且展示了构造函数中session_table参数的用法——Workflow 使用独立命名空间避免与 Agent/Team 的会话表冲突content_creation_workflow Workflow( nameContent Creation Workflow, descriptionAutomated content creation from blog posts to social media, dbPostgresDb( session_tableworkflow_session, db_urldb_url, ), steps[research_step, content_planning_step], ) content_creation_workflow.print_response( inputAI trends in 2024, markdownTrue, )示例流程包含两个步骤research_step由 HackerNews 与 Web 两个 Agent 组成的research_team执行研究与content_planning_step由content_planner制定四周内容计划。由于 Workflow 本身不依赖轮询式对话而是逐步推进把中间状态持久化到数据库能让长流程具备断点恢复与可观测性。异步方案AsyncPostgresDb在高并发或 IO 密集场景下Agno 提供了AsyncPostgresDbAPI 设计与PostgresDb对齐只是驱动连接串换用异步协议。原文档最小配置from agno.agent import Agent from agno.db.postgres import AsyncPostgresDb db AsyncPostgresDb(db_urlpostgresqlpsycopg_async://username:passwordlocalhost:5432/database) agent Agent( dbdb, add_history_to_contextTrue, )请留意连接串从postgresqlpsycopg变为postgresqlpsycopg_async这是同步/异步方案最重要的差别。异步用例如 async_postgres_for_agent.py 所示整个驱动链路由asyncio协调import asyncio from agno.agent import Agent from agno.db.postgres import AsyncPostgresDb db_url postgresqlpsycopg_async://ai:ailocalhost:5532/ai db AsyncPostgresDb(db_urldb_url) agent Agent( dbdb, tools[WebSearchTools()], add_history_to_contextTrue, add_datetime_to_contextTrue, ) async def main(): await agent.aprint_response(How many people live in Canada?) await agent.aprint_response(What is their national anthem called?) if __name__ __main__: asyncio.run(main())配套的异步示例还有两个async_postgres_for_team.py结构上与同步 Team 示例一致仅将hn_team.print_response(...)替换为asyncio.run(hn_team.aprint_response(...))async_postgres_for_workflow.py将同一个AsyncPostgresDb实例传入Workflow(dbdb, ...)并通过asyncio.run(content_creation_workflow.aprint_response(...))执行。AsyncPostgresDb的实现位于 libs/agno/agno/db/postgres/async_postgres.py与PostgresDb共享同一套 schema 与表结构设计二者之间可以按需切换而不必改动业务逻辑仅需更换连接串与调用前缀a。运行验证与排障要点准备一个可用的 PostgreSQL 实例后可按如下顺序验证# 1. 安装依赖同步示例 uv pip install psycopg2-binary sqlalchemy openai ddgs # 2. 运行 Agent 示例首次启动会自动建表 python cookbook/06_storage/postgres/postgres_for_agent.py # 3. 运行 Workflow 示例 python cookbook/06_storage/postgres/postgres_for_workflow.py # 4. 异步方案换用异步驱动 uv pip install psycopg sqlalchemy openai python cookbook/06_storage/postgres/async_postgres/async_postgres_for_agent.py常见问题与排查方向连不上数据库确认db_url中端口默认5432示例脚本用5532、账号密码与库名正确且目标库已存在sqlalchemy not installed报错PostgresDb强依赖 SQLAlchemy需显式安装异步示例另需psycopg同步为psycopg2-binary连接串协议错误同步用postgresqlpsycopg://异步用postgresqlpsycopg_async://切勿混用表冲突Agent/Team/Workflow 会话可分别通过session_table指定独立表如workflow_session避免不同主体的会话数据互相覆盖跨进程恢复会话数据库存储后配合 session_id 管理可在新进程中恢复既有会话相关基础用法可对照 cookbook/06_storage/01_persistent_session_storage.py 验证。小结Agno 将 PostgreSQL 存储封装为一行式配置同步场景使用PostgresDbpostgresqlpsycopg://异步场景使用AsyncPostgresDbpostgresqlpsycopg_async://二者均可直接挂载到 Agent、Team 与 Workflow 上配合add_history_to_context实现会话级记忆与多轮连续性。仓库源码层面连接策略db_engine优先、其次db_url、自动建表开关create_schema以及 session/runs/memory/metrics/traces 等分表参数都已内置足以支撑从本地原型到生产部署的平滑演进。你可以在 cookbook/06_storage/postgres 目录中继续查阅全部同步与异步示例源码。【免费下载链接】agnoBuild, run, and manage agent platforms.项目地址: https://gitcode.com/GitHub_Trending/ag/agno创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考