dansewer 开源项目 Terraform Provider 的 Onyx Agent(Persona)资源完整指南:从原理到实战

原创2026-10-10 16:59:251,677 阅读
文章标签:人工智能AI 应用RAGAI Agent深度研究MCP 服务知识库搜索引擎企业应用后端前端数据集成

dansewer 开源项目 Terraform Provider 的 Onyx Agent(Persona)资源完整指南:从原理到实战

导读

本文围绕 dansewer 开源项目(Onyx AI 平台)提供的 Terraform Provider terraform-provider-onyx 中的 onyx_agent 资源(历史名称为 onyx_persona,即 Onyx 的"助理/Agent"对象)展开:先讲清它在 Onyx 体系中的定位与底层 REST 实现,再逐字段剖析资源 Schema,最后通过完整可运行的 Terraform 配置示例、导入方法与测试用例,带你掌握用 IaC 方式声明式管理 Onyx 助理(指令 + 知识 + 动作 + 可见性 + 精选排位)的全部实战能力。

Onyx Agent 资源是什么:从 /persona 到 onyx_agent 的演进

在 Onyx 产品中,用户所称的"Agent(助理)"是一组命名指令、知识与动作的组合,用户可以直接与其对话。Terraform Provider 用 onyx_agent 资源来管理它。需要特别说明的是命名演变:Provider 在 0.3.0 版本(见 CHANGELOG.md)把资源从 onyx_persona 重命名为 onyx_agent,因为 Onyx 面向用户的所有界面都已使用"agent"这一称谓,REST API 也在向同一方向演进。

但底层线缆格式(wire format)完全没有变:Onyx 后端仍然在 /persona 路径下提供 create/read/update/delete 与 listed 操作,JSON 字段仍沿用 personas、builtin_persona 的旧拼写。这一点在 agent.go 的注释中写得很明确:

"Onyx calls this resource an 'agent', but only the list and display-priority routes are served under /admin/agents. Create, read, update, delete and listed still live under /persona... Do not rewrite those paths or tags to match the Go names: the /admin/agents prefix has no equivalent for them, so the calls would 404 against every released Onyx."

也就是说:只改了 Terraform 侧的名字,REST 路径与 JSON 字段名保持旧版不变,因此 0.3.0 版本的 Provider 与 0.2.0 所兼容的 Onyx 后端完全相同。对应地,Provider 返回的只读字段 builtin_agent 在 JSON 层面对应 builtin_persona,用户组的 persona_ids 也同步更名为 agent_ids。

名称唯一性与 Tombstone(墓碑)机制——最重要的语义

onyx_agent 有两个由 Onyx 后端行为决定的硬性约束:

  1. Agent 名称在整个部署范围内唯一。创建时若与其他"存活"(未删除)的 agent 重名,请求会被直接拒绝。
  2. 删除 agent 只会留下一个 tombstone(墓碑)。Onyx 并不真正删除数据库行,而是标记为已删除,因此名称仍然被占用。此后若再次以该名称创建 agent,不会新建对象,而是**"复活"这个墓碑,并保留其原始 id**。这正是"先 destroy 再 apply 会得到同一个 agent id"的原因。

从源码看,CreateAgent 是按名称匹配的(agent.go):

// Onyx matches a create by name: a name another live agent holds is rejected,
// and a name held only by a deleted agent revives that agent, id and all.
func (c *Client) CreateAgent(ctx context.Context, req AgentWrite) (*Agent, error) {
	var agent Agent
	if err := c.doJSON(ctx, http.MethodPost, "/persona", req, &agent); err != nil {
		return nil, err
	}
	return &agent, nil
}

而 DeleteAgent 的注释也直接点明了 tombstone 行为(agent.go):

// The row survives as a tombstone: it stops answering reads, but it keeps its
// name and its attached actions. Creating an agent under the same name later
// revives this one rather than making a new one.
func (c *Client) DeleteAgent(ctx context.Context, id int64) error {
	return c.doJSON(ctx, http.MethodDelete, fmt.Sprintf("/persona/%d", id), nil, nil)
}

实战影响:如果某次 terraform destroy 失败,名称并不会被释放,下次 apply 仍可能复活旧 agent。测试套件为此专门使用了带随机前缀的名称(acctest.RandomWithPrefix("tf-acc-agent")),见 agent_resource_test.go,以保证测试可重复运行。你的生产配置同样建议用可预测、可协商的唯一名称,避免误复活。

另外一个易踩的坑:已删除 agent 返回 400 而非 404

Onyx 对不存在的(或已删除的)agent 返回 HTTP 400,而不是 404——后端查找时抛出一个普通的 ValueError,被渲染为 bad request。因此 Provider 的 LookupAgent 不能直接根据错误状态码判断"对象已消失",而是先读一次,失败后再查 agent 列表来确认(agent.go):

func (c *Client) LookupAgent(ctx context.Context, id int64) (*Agent, bool, error) {
	agent, err := c.GetAgent(ctx, id)
	if err == nil {
		return agent, true, nil
	}
	if IsNotFound(err) {
		return nil, false, nil
	}
	listed, listErr := c.agentIsListed(ctx, id)
	if listErr == nil && !listed {
		return nil, false, nil
	}
	return nil, false, err
}

同样的逻辑也用于 Delete:当删除返回错误(tombstone 导致的权限类错误)时,Provider 会先通过 LookupAgent 确认对象是否真的已经不在了,再决定是否把 destroy 当作成功处理(agent_resource.go)。README 将该限制标注为"Fixed upstream"——后端新版本将返回类型化的 PERSONA_NOT_FOUND。

完整示例配置:三个可直接上手的实战场景

以下是 agent.md 中给出的三类典型用法,覆盖了公开客服助理、私有(企业版)助理与精选助理:

场景一:面向全员的公开客服助理

# An agent (assistant) pairs instructions with the knowledge and actions it may
# use. Agent names are unique across the deployment.
resource "onyx_agent" "support" {
  name        = "Support"
  description = "Answers customer questions from the handbook"

  system_prompt = <<-EOT
    You are a support agent. Answer from the handbook only.
    If the handbook does not cover the question, say so and offer to escalate.
  EOT

  # Appended to each user message.
  task_prompt = "Cite the handbook section you used."

  document_set_ids = [onyx_document_set.handbook.id]
  tool_ids         = [onyx_custom_tool.weather.id]

  starter_messages = [
    {
      name    = "Refunds"
      message = "How do refunds work?"
    },
    {
      name    = "Shipping"
      message = "How long does shipping take?"
    },
  ]
}

场景二:仅限指定组/用户使用的私有助理(Enterprise Edition)

# An agent that only its group may use, kept out of the assistant list.
resource "onyx_agent" "hr_private" {
  name          = "HR"
  description   = "Answers policy questions for the HR team"
  system_prompt = "You answer HR policy questions."

  document_set_ids = [onyx_document_set.hr_private.id]

  # A hidden agent still works for anyone holding a link to it.
  is_listed = false

  # Private agents need Enterprise Edition. Group and user ids come from the
  # deployment, so read them from the admin panel or pass them in.
  is_public = false
  groups    = [4]
  users     = [var.hr_lead_user_id]
}

场景三:带排位与时间过滤的精选(Featured)助理

# Onyx promotes a featured agent to users. Ignoring documents from before a
# migration keeps an agent off stale material.
resource "onyx_agent" "onboarding" {
  name          = "Onboarding"
  description   = "Walks new starters through their first week"
  system_prompt = "You help new employees get set up."

  document_set_ids  = [onyx_document_set.handbook.id]
  is_featured       = true
  display_priority  = 1
  icon_name         = "user"
  search_start_date = "2026-01-01"
}

运行前提:Provider 认证

在运行以上配置前,需要先声明 Provider。API key 必须属于内置的 Admin 组(或以管理员身份创建的不受限 PAT,形如 onyx_pat_...),具体见 README.md 的 Authentication 一节:

terraform {
  required_providers {
    onyx = {
      source = "onyx-dot-app/onyx"
    }
  }
}

variable "onyx_api_key" {
  type      = string
  sensitive = true
}

# 也可以通过 ONYX_SERVER_URL / ONYX_API_KEY 环境变量提供凭证
provider "onyx" {
  endpoint = "https://onyx.internal.example.com"
  api_key  = var.onyx_api_key # Admin 组的 API key("on_...")
}

补充说明:api_prefix 默认为 /api(走 Web 代理);当直接指向后端(如 http://localhost:8080)时应设为 "",同样可用 ONYX_API_PREFIX 环境变量覆盖(docs/index.md)。

Schema 全字段详解:参数、默认值与底层行为

资源 Schema 定义于 agent_resource.go,以下为完整字段清单,均同时补充了后端行为解释。

Required(必填)

字段 类型 说明
name String Agent 名称,部署范围内必须唯一。

Optional(可选)

字段 类型 默认值 说明
datetime_aware Boolean false 是否告知 agent 当前日期与时间。
default_model_configuration_id String 未设置 agent 使用的模型配置 id;不设置则使用部署默认模型。
description String "" 一行简介,显示在 agent 卡片上。
display_priority Number — 助理列表中的排序位置,数值越小越靠前。Onyx 只在创建时读取该值,后续改动通过独立的 display-priority 端点以第二次调用的方式生效;从配置中移除该属性时,保留最后一次写入的值而不是清空。
document_set_ids Set of String — agent 可搜索的文档集 id,例如 [onyx_document_set.handbook.id]。
groups Set of Number — 非公开 agent 可使用的用户组 id。仅 Enterprise Edition。
icon_name String — agent 卡片上显示的内置图标名称。
is_featured Boolean false 是否由 Onyx 向用户推广该 agent。需要 agent 管理权限。
is_listed Boolean true 是否出现在助理列表中。隐藏的 agent 仍可被任何持有其链接的人使用。由于 Onyx 通过独立端点设置该值,Terraform 会在写入 agent 之后以第二次 API 调用应用它。
is_public Boolean true 是否所有用户都能使用。为 false 时仅 users 与 groups 可用。
label_ids Set of Number — agent 归类的标签 id;标签在管理后台创建。
replace_base_system_prompt Boolean false 是否单独使用 system_prompt,而不是叠加在 Onyx 基础 prompt 之上。替换基础 prompt 会丢掉让引用(citation)与搜索工作的指令,除非 agent 需要完全控制,否则保持关闭。
search_start_date String — 忽略早于该日期的文档,格式为 YYYY-MM-DD 或完整时间戳。
starter_messages List of Attributes — 建议的起始提问,按给定顺序展示(嵌套结构见下)。
system_prompt String "" agent 的指令,叠加在系统 prompt 上。
task_prompt String "" 附加到每条用户消息的额外指令。
tool_ids Set of String — agent 可调用的动作 id,例如 [onyx_custom_tool.weather.id]。Onyx 会把自己 API 响应中的两个内置动作排除在外,因此挂载其中一个会导致永久性差异(永远无法收敛);请挂载自定义动作和普通内置动作。
users Set of String — 非公开 agent 可使用的用户 id(UUID)。仅 Enterprise Edition。

Read-Only(只读)

字段 类型 说明
builtin_agent Boolean 该 agent 是否为 Onyx 内置。内置 agent 在部署中配置,不通过 API 管理(JSON 字段名为 builtin_persona)。
id String 数字形式的 agent id。

嵌套结构:starter_messages

starter_messages 为对象列表,每个对象包含两个必填字段:

  • message(String,必填):用户选中后发送的消息内容;
  • name(String,必填):按钮上显示的短标签。

Provider 用 starterMessageModel 与固定属性表 starterMessageAttrTypes 来构造/解析该列表(agent_resource.go)。

关键字段的源码级行为说明

  • search_start_date 是"只写不读"字段。Onyx 的 PersonaSnapshot 不返回 search_start_date(agent.go),因为后端会把它解析成时间戳返回。若 Provider 读回并回写,会把普通日期改写成另一种形式,导致每次 plan 都报告差异。因此 applyRemoteAgent 对该字段不做回写(agent_resource.go),每次 apply 都会重发配置中的值。这也意味着在管理后台对该字段的外部改动,terraform plan 无法探测。
  • 写请求是全量替换。writeFromModel 会把所有受管字段一次全部发送(agent_resource.go),对应后端 PersonaUpsertRequest 同时被 create 与 update 使用。服务端部分字段是"null 表示保持不变"的三态语义,但 Provider 管理整个 agent,所以每次都发送全部值,三态不会进入实际流程。
  • is_listed 与 display_priority 走独立端点。创建/更新主请求不携带这两个值(新 agent 默认一定被列出),Provider 在写入 agent 后分别调用 PATCH /admin/persona/{id}/listed 与 PATCH /admin/agents/display-priorities(后者接受一个 display_priority_map,只影响映射中列出的 agent)——实现见 SetAgentListed / SetAgentDisplayPriority(agent.go)与 applyListed / applyDisplayPriority(agent_resource.go)。失败时先写状态再报错,保证已创建的 agent 仍被跟踪。
  • 更新会保护非受管字段。HierarchyNodeIDs(文件夹,用于限定范围搜索)与 DocumentIDs(文档)不由 Terraform 管理:省略列表会清空服务端数据,显式 null 会被后端以 422 拒绝("Input should be a valid list")。因此 Update 会先 GetAgent 读回这两个字段并原样回写(agent_resource.go),只留下一个"读写间隙内新增的附件会被回滚"的窄窗口。README 标注该限制已在上游修复为可空字段。
  • tool_ids 的两个隐藏内置动作是 OktaProfileTool 与 MemoryTool:Onyx 不把它们放进 agent snapshot,所以挂载它们的 agent 读回的 tool_ids 少于写入值,永远无法收敛。README 的 Known limitations 一节明确建议改用自定义动作与其他内置动作。

后端 API 的印证:Onyx 如何校验这些字段

Terraform Provider 的字段语义与 Onyx 后端的 api.py 一一对应。后端在 /persona(basic)与 /admin/persona(admin)两组路由下提供接口,并新增了 agents_router(ADMIN_AGENTS_RESOURCE)用于列表与排位;注释同样说明用户侧称之为 "agents",REST 命名正在逐步迁移(api.py)。

is_listed 独立端点的服务端实现正是 PATCH /admin/persona/{persona_id}/listed,且要求 MANAGE_AGENTS 权限(api.py),这与 Provider 侧 is_featured 需要 agent 管理权限的约束相互印证。

后端还会在 upsert 时做两类校验,Terraform 配置时值得留意:

  • _validate_user_knowledge_enabled:当 workspace 未启用 User Knowledge 时,若请求携带 user_file_ids/user_project_ids 会被 400 拒绝(api.py);
  • _validate_vector_db_knowledge:当设置了 DISABLE_VECTOR_DB 时,document_set_ids、hierarchy_node_ids、document_ids 均被拒绝(用户文件走 FileReaderTool 路径,不受影响)——见 api.py。这说明"挂文档集"这类能力依赖向量数据库的运行状态。

导入现有 Agent:terraform import 用法

onyx_agent 支持通过 terraform import 引入存量 agent,按数字 agent id 导入(agent.md):

#!/bin/sh
# Import by numeric agent id.
terraform import onyx_agent.support 4

导入实现是 ImportStatePassthroughID,直接把 id 透传给 id 属性(agent_resource.go)。导入后首次 apply 会用服务端快照填充各字段;如涉及 search_start_date 等只写字段,请按前文说明留意其"配置值在每次 apply 重发"的行为。

从 onyx_persona 升级:0.3.0 迁移步骤

如果你的存量配置还在使用旧名 onyx_persona,升级 Provider 到 0.3.0 时需要在配置与状态中同时改名(CHANGELOG.md):

terraform state mv onyx_persona.example onyx_agent.example

同步发生的更名包括:builtin_persona → builtin_agent、onyx_user_group 的 persona_ids → agent_ids、onyx_llm_provider 的 personas → agents。由于线缆格式不变,该版本与 0.2.0 兼容的 Onyx 版本完全相同,无需担心后端联动升级。

测试验证:Provider 如何保证上述行为

agent_resource_test.go 的验收测试完整覆盖了资源生命周期,可作为你理解行为的对照:

  • 创建:断言 name/description/system_prompt/task_prompt/is_public(默认 true)/is_listed(通过 follow-up 调用置 false)/is_featured(默认 false)/display_priority/builtin_agent(默认 false)/tool_ids/starter_messages 等值,并验证未设置的 document_set_ids、users、groups、icon_name 保持 null(否则每次 plan 都会报差异)。
  • 全量替换更新:重命名、删除 description 与 task_prompt、清空 tool_ids 与 starter_messages、重新 listed,并验证 display_priority 从 5 改为 2(证明触发 display-priority 独立端点的第二次调用确实执行)。
  • 重名拒绝:TestAccAgentResourceRejectsADuplicateName 用两个同名资源验证创建被拒,错误信息匹配 already exists(agent_resource_test.go)。
  • 销毁确认:testAccCheckAgentDestroyed 通过 LookupAgent 确认对象真的消失(tombstone 后读不到)。

与 Provider 其他资源的协作关系

onyx_agent 常与其他资源组合使用,形成完整链路(资源清单见 README.md):

  • onyx_custom_tool:为 agent 提供可调用的自定义动作(tool_ids 引用其 .id);
  • onyx_document_set:为 agent 划定可搜索的知识范围(document_set_ids 引用其 .id);
  • onyx_llm_provider / onyx_llm_provider_default:决定 agent 实际使用的模型;
  • onyx_user_group:非公开 agent 的授权对象之一(其只读 agent_ids 与 agent 上的 groups 各自拥有链路,互不冲突)。

examples/bootstrap 提供了一套可直接运行的首日配置:聊天模型、一个被索引的站点、由其构建的文档集,以及一个基于该文档集回答问题的 agent,是理解整套 Provider 用法的最佳起点。

结语

onyx_agent 是 terraform-provider-onyx 中管理 Onyx 助理的核心资源,其语义高度依赖后端 /persona 接口的行为:名称唯一、删除留墓碑、部分字段走独立端点、部分字段只写不读。理解这些底层约束(对应 agent_resource.go、agent.go 与 api.py 的实现)后再编写 Terraform 配置,就能避开重名复活、永久差异、字段被外部改动等常见陷阱,把助理的指令、知识、动作与可见性全部纳入 IaC 管理闭环。

登录后查看全文
danswer