Local Agent

本地 Agent 快速开始

用 Agent SDK 在本地进程里创建一个可执行的 Agent,并理解本地模型与 Federation AIService 模型的差异

本地 Agent 快速开始

安装

pnpm add @downcity/agent

最小示例

import { Agent } from "@downcity/agent";
import { createOpenAI } from "@ai-sdk/openai";

const openai = createOpenAI({
  apiKey: process.env.OPENAI_API_KEY!,
});

const agent = new Agent({
  id: "repo-helper",
  path: "/path/to/project",
  tools: {},
  prepare_session: async (session) => {
    await session.set({ model: openai.responses("gpt-5") });
  },
});

const session = await agent.sessions.create();
const turn = await session.prompt({
  query: "总结一下当前仓库结构",
});

const result = await turn.finished;
console.log(result.text);

最重要的三步

  1. new Agent(...)
  2. await agent.sessions.create()
  3. 确保 session 有 model

这三步里第 3 步最容易被遗漏,也是本地 SDK 最常见的踩坑点。

第 3 步有两种做法:

  • 由宿主通过 prepare_session 注入运行时模型
  • 或者对某个本地 Session 单独调用 await session.set({ model })

如果两种都没做,本地 session 没有模型,无法执行。

一个关键区分

纯 SDK 嵌入模式

如果你是直接把 @downcity/agent 嵌到自己的 Node 应用里,最常见就是:

  • new Agent({ prepare_session })
  • 或本地 session.set({ model })

模型实例由你的宿主代码直接持有。

Downcity Agent 项目模式

如果你是在正常的 Downcity / Downcity 项目里跑 Agent,通常不应该在项目里直接持有 provider 配置或模型实例。

这时模型来自:

  • Agent config execution.modelId
  • 已连接的 Federation AIService

也就是说:

  • Agent 项目只选择 modelId
  • Federation AIService 管理 provider、API key、模型目录

Agent 的生命周期

new Agent(...) 之后,plugin lifecycle 与 ActionSchedule 会立即开始启动。调用方通常直接:

const session = await agent.sessions.create();
const turn = await session.prompt({ query: "hello" });
await turn.finished;

Session 入口内部已经隐式等待当前 Agent 的后台启动;模型开始执行前,plugin lifecycle 已完成。await agent.ready() 仍然可以作为显式检查点使用,适合在构造后立刻读取 plugin 状态或暴露 RPC / HTTP 服务前调用。

不再使用时调用 await agent.dispose(),会停掉 plugin lifecycle、ActionSchedule、shell 等后台资源。

如果需要把当前 Agent 暴露给其他进程使用(RPC 或 HTTP),请使用独立包 @downcity/server。Agent 自身不再启动任何 transport。

继续阅读