getCurrentAgent() 函数允许你从代码任意位置(包括外部工具函数和库)访问当前 Agent 上下文。当你需要在无法直接访问 this 的函数中获取 Agent 信息时,这很有用。
框架在初始化期间检测并包装自定义 Agent 方法,使 getCurrentAgent() 能在这些方法及其调用的函数内解析活动 Agent。
import { AIChatAgent } from "@cloudflare/ai-chat";
import { getCurrentAgent } from "agents";
export class MyAgent extends AIChatAgent {
async customMethod() {
const { agent } = getCurrentAgent();
// agent is automatically available
console.log(agent.name);
}
async anotherMethod() {
// This works too - no setup needed
const { agent } = getCurrentAgent();
return agent.state;
}
}import { AIChatAgent } from "@cloudflare/ai-chat";
import { getCurrentAgent } from "agents";
export class MyAgent extends AIChatAgent {
async customMethod() {
const { agent } = getCurrentAgent();
// agent is automatically available
console.log(agent.name);
}
async anotherMethod() {
// This works too - no setup needed
const { agent } = getCurrentAgent();
return agent.state;
}
}无需配置。框架自动:
- 扫描 Agent 类中的自定义方法。
- 在初始化期间用 Agent 上下文包装它们。
- 确保
getCurrentAgent()在从方法调用的所有外部函数中可用。
import { AIChatAgent } from "@cloudflare/ai-chat";
import { getCurrentAgent } from "agents";
import { generateText } from "ai";
import { openai } from "@ai-sdk/openai";
// External utility function that needs agent context
async function processWithAI(prompt) {
const { agent } = getCurrentAgent();
// External functions can access the current agent
return await generateText({
model: openai("gpt-4"),
prompt: `Agent ${agent?.name}: ${prompt}`,
});
}
export class MyAgent extends AIChatAgent {
async customMethod(message) {
// Use this.* to access agent properties directly
console.log("Agent name:", this.name);
console.log("Agent state:", this.state);
// External functions automatically work
const result = await processWithAI(message);
return result.text;
}
}import { AIChatAgent } from "@cloudflare/ai-chat";
import { getCurrentAgent } from "agents";
import { generateText } from "ai";
import { openai } from "@ai-sdk/openai";
// External utility function that needs agent context
async function processWithAI(prompt: string) {
const { agent } = getCurrentAgent();
// External functions can access the current agent
return await generateText({
model: openai("gpt-4"),
prompt: `Agent ${agent?.name}: ${prompt}`,
});
}
export class MyAgent extends AIChatAgent {
async customMethod(message: string) {
// Use this.* to access agent properties directly
console.log("Agent name:", this.name);
console.log("Agent state:", this.state);
// External functions automatically work
const result = await processWithAI(message);
return result.text;
}
}- 内置方法(
onRequest、onEmail、onStateChanged):已有上下文。 - 自定义方法(你的方法):初始化期间自动包装。
- 外部函数:通过
getCurrentAgent()访问上下文。
// When you call a custom method:
agent.customMethod();
// → automatically wrapped with agentContext.run()
// → your method executes with full context
// → external functions can use getCurrentAgent()// When you call a custom method:
agent.customMethod();
// → automatically wrapped with agentContext.run()
// → your method executes with full context
// → external functions can use getCurrentAgent()import { AIChatAgent } from "@cloudflare/ai-chat";
import { generateText } from "ai";
import { openai } from "@ai-sdk/openai";
export class MyAgent extends AIChatAgent {
async generateResponse(prompt) {
// AI SDK tools automatically work
const response = await generateText({
model: openai("gpt-4"),
prompt,
tools: {
// Tools that use getCurrentAgent() work perfectly
},
});
return response.text;
}
}import { AIChatAgent } from "@cloudflare/ai-chat";
import { generateText } from "ai";
import { openai } from "@ai-sdk/openai";
export class MyAgent extends AIChatAgent {
async generateResponse(prompt: string) {
// AI SDK tools automatically work
const response = await generateText({
model: openai("gpt-4"),
prompt,
tools: {
// Tools that use getCurrentAgent() work perfectly
},
});
return response.text;
}
}import { AIChatAgent } from "@cloudflare/ai-chat";
import { getCurrentAgent } from "agents";
async function saveToDatabase(data) {
const { agent } = getCurrentAgent();
// Can access agent info for logging, context, etc.
console.log(`Saving data for agent: ${agent?.name}`);
}
export class MyAgent extends AIChatAgent {
async processData(data) {
// External functions automatically have context
await saveToDatabase(data);
}
}import { AIChatAgent } from "@cloudflare/ai-chat";
import { getCurrentAgent } from "agents";
async function saveToDatabase(data: any) {
const { agent } = getCurrentAgent();
// Can access agent info for logging, context, etc.
console.log(`Saving data for agent: ${agent?.name}`);
}
export class MyAgent extends AIChatAgent {
async processData(data: any) {
// External functions automatically have context
await saveToDatabase(data);
}
}import { getCurrentAgent } from "agents";
function logRequestInfo() {
const { agent, connection, request } = getCurrentAgent();
if (request) {
console.log("Request URL:", request.url);
console.log("Request method:", request.method);
}
if (connection) {
console.log("Connection ID:", connection.id);
}
}import { getCurrentAgent } from "agents";
function logRequestInfo() {
const { agent, connection, request } = getCurrentAgent();
if (request) {
console.log("Request URL:", request.url);
console.log("Request method:", request.method);
}
if (connection) {
console.log("Connection ID:", connection.id);
}
}Agent 上下文仅沿原始调用的调用树传播。在该调用树之外到达的代码以空上下文开始,因此 getCurrentAgent() 返回各字段为 undefined 的对象。常见情况包括:
- 通过 Worker Loader 子 isolate 的 RPC 调用的宿主回调,例如沙箱化 Codemode execution;
- service binding 或 Durable Object RPC 入口点;
- 保留 Agent 引用的 queue consumer 或其他入口点。
将回调路由到 Agent 上的公共方法。自定义方法自动包装,因此调用 agent.someMethod() 会重新进入该 Agent 的上下文:
import { RpcTarget } from "cloudflare:workers";
class HostCallbackBridge extends RpcTarget {
agent;
constructor(agent) {
super();
this.agent = agent;
}
// Invoked through RPC from a Worker Loader child isolate. There is no context
// ancestry. Calling a public agent method restores it automatically.
async invoke() {
return this.agent.handleSandboxCallback();
}
}
export class MyMcpAgent extends McpAgent {
async handleSandboxCallback() {
const { agent } = getCurrentAgent();
// `agent` is available again.
}
}import { RpcTarget } from "cloudflare:workers";
class HostCallbackBridge extends RpcTarget {
agent: MyMcpAgent;
constructor(agent: MyMcpAgent) {
super();
this.agent = agent;
}
// Invoked through RPC from a Worker Loader child isolate. There is no context
// ancestry. Calling a public agent method restores it automatically.
async invoke() {
return this.agent.handleSandboxCallback();
}
}
export class MyMcpAgent extends McpAgent {
async handleSandboxCallback() {
const { agent } = getCurrentAgent<MyMcpAgent>();
// `agent` is available again.
}
}以此方式恢复的上下文中 connection、request 和 email 未设置。它不绑定到实时客户端 I/O。
McpAgent 上的服务端发起 MCP 请求(elicitInput、createMessage 和 listRoots)不需要此间接方式,因为 MCP 传输保留其所属 Agent。
从任何可用上下文中获取当前 Agent。
import { getCurrentAgent } from "agents";import { getCurrentAgent } from "agents";
function getCurrentAgent<T extends Agent>(): {
agent: T | undefined;
connection: Connection | undefined;
request: Request | undefined;
email: AgentEmail | undefined;
};| 属性 | 类型 | 描述 |
|---|---|---|
agent |
T | undefined |
当前 Agent 实例 |
connection |
Connection | undefined |
WebSocket 连接(若从 WebSocket handler 调用) |
request |
Request | undefined |
HTTP 请求(若从 request handler 调用) |
email |
AgentEmail | undefined |
邮件(若从 email handler 调用) |
import { AIChatAgent } from "@cloudflare/ai-chat";
import { getCurrentAgent } from "agents";
export class MyAgent extends AIChatAgent {
async customMethod() {
const { agent, connection, request } = getCurrentAgent();
// agent is properly typed as MyAgent
// connection and request available if called from a request handler
}
}import { AIChatAgent } from "@cloudflare/ai-chat";
import { getCurrentAgent } from "agents";
export class MyAgent extends AIChatAgent {
async customMethod() {
const { agent, connection, request } = getCurrentAgent<MyAgent>();
// agent is properly typed as MyAgent
// connection and request available if called from a request handler
}
}可用上下文取决于方法的调用方式:
| 调用 | agent |
connection |
request |
email |
|---|---|---|---|---|
onRequest() |
是 | 否 | 是 | 否 |
onConnect() |
是 | 是 | 是 | 否 |
onMessage() |
是 | 是 | 否 | 否 |
onEmail() |
是 | 否 | 否 | 是 |
| 自定义方法(通过 RPC) | 是 | 是 | 否 | 否 |
| 调度任务 | 是 | 否 | 否 | 否 |
| Queue 回调 | 是 | 视情况 | 视情况 | 视情况 |
-
尽可能使用
this:在 Agent 方法内,优先使用this.name、this.state等,而非getCurrentAgent()。 -
在外部函数中使用
getCurrentAgent():当你需要在无法访问this的工具函数或库中获取 Agent 上下文时。 -
检查 undefined:若在 Agent 上下文外调用,返回值可能为
undefined。const { agent } = getCurrentAgent(); if (agent) { // Safe to use agent console.log(agent.name); }const { agent } = getCurrentAgent(); if (agent) { // Safe to use agent console.log(agent.name); } -
为 Agent 指定类型:传入 Agent 类作为类型参数以获得正确类型。
const { agent } = getCurrentAgent(); // agent is typed as MyAgent | undefinedconst { agent } = getCurrentAgent<MyAgent>(); // agent is typed as MyAgent | undefined